1

I have a json array in my table. It contains an array. I can create, append or make my array NULL. Inside my stored procedure but I don't see any way to pop value from array. Apparently JSON_Modify may have solution as you can update key as well as Single value but how can I use it to modify my array?

--My Array 
Declare @json = '{"array":[123,456]}'

Desired results after update:

'{"array":[123]}'

Please note that array contain int values. Which are my sub department id. All values are (supposed to be) unique.

2 Answers 2

1

You could use:

DECLARE @json NVARCHAR(MAX) = '{"array":[123,456]}';

WITH cte AS (
  SELECT *, MAX([key]) OVER() AS m_key
  FROM OPENJSON(@json, '$.array') s
)
SELECT JSON_QUERY('[' + IIF(MAX(m_key) = 0, '', STRING_AGG(value,',') 
                   WITHIN GROUP (ORDER BY [key])) + ']','$') AS array
FROM cte
WHERE [key] != m_key OR m_key = 0
FOR JSON AUTO, WITHOUT_ARRAY_WRAPPER;

Output:

{"array":[123]}

DBFiddle Demo SQL Server 2017

Sign up to request clarification or add additional context in comments.

6 Comments

Work like a charm, though in hurry I completed my work using XML Path which is weird using XML with JSON.
@abdulqayyum Great to hear that you solved your question anyway :)
I have added my solution just for comparison.
@lad2025 which is minimum version of SQL Server that supports OPENJSON ?
@abdulqayyum I modified my answer slightly to handle one element array. JSON is supported from SQL Server 2016
|
1

As I was in hurry I solved my problem following way, but I would really recommend not to use it. Please see answer above by @lad2025.

DECLARE @json VARCHAR(MAX)
                          =(SELECT jsonDept 
                            FROM tblEmployee 
                            WHERE tblEmployeeID = @empid)
    DECLARE @newjson VARCHAR(MAX)= (
    SELECT LEFT(subdept, LEN(subdept)-1)
    FROM (
    SELECT Distinct value + ', ' FROM OPENJSON(@json,'$.array') Where value <> @subdeptid
    FOR XML PATH ('')
    ) t (subdept))
    UPDATE tblEmployee SET jsonDept = '{"array":['+ @newjson +']}' WHERE tblEmployeeID = @empid

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.