1

I am stuck on updating/inserting rows from json array into SQL Server 2017.

I have the following structure:

{
    "ID":52,
    "Name":"Mark",
   "Surname":"Blake",
    "Age": 24
    "Cars":[
         {"ID":110,"Volvo":"2001-10-01","Color":"red"},
         {"ID":110,"Volvo":"2001-10-01","Color":"red"},
         {"ID":110,"Volvo":"2001-10-01","Color":"red"},
         {"ID":-1,"Volvo":"2001-10-01","Color":"red"},
         {"ID":-1,"Volvo":"2001-10-01","Color":"red"},
    ]
}

I am trying to do a merge basing on Cars array, when ID is -1 then insert to table, else update.

How to achieve this?

OK, I did it, but I've got an another problem. I'd like to get also ID from higher level (I mean 52 in this case), it should looks like:

110 52 2001-10-01  red
110 52 2001-10-01  red
110 52 2001-10-01  red
-1  52 2001-10-01  red
-1  52 2001-10-01  red

1 Answer 1

1

I fixed you JSON, it was a bit incorrect.

DECLARE @json nvarchar(max) = '{
    "ID":52,
    "Name":"Mark",
   "Surname":"Blake",
    "Age": 24,
    "Cars":[
         {"ID":110,"Volvo":"2001-10-01","Color":"red"},
         {"ID":110,"Volvo":"2001-10-01","Color":"red"},
         {"ID":110,"Volvo":"2001-10-01","Color":"red"},
         {"ID":-1,"Volvo":"2001-10-01","Color":"red"},
         {"ID":-1,"Volvo":"2001-10-01","Color":"red"}
    ]
}'


SELECT  JSON_VALUE(t.[value], N'$.ID'),
        JSON_VALUE(t.[value], N'$.Volvo'),
        JSON_VALUE(t.[value], N'$.Color')
FROM OPENJSON(@json, N'$.Cars') as t

Output:

110 2001-10-01  red
110 2001-10-01  red
110 2001-10-01  red
-1  2001-10-01  red
-1  2001-10-01  red

Put that in CTE or temp table, then MERGE the primary table. Or you can at first INSERT (WHERE ID = -1) and UPDATE (WHERE ID != -1)

Update:

SELECT  f.[value],
        JSON_VALUE(c.[value], N'$.ID'),
        JSON_VALUE(c.[value], N'$.Volvo'),
        JSON_VALUE(c.[value], N'$.Color')
FROM OPENJSON(@json) f
CROSS APPLY OPENJSON(@json,N'$.Cars') c
WHERE f.[key] IN ('ID')

Output:

52  110 2001-10-01  red
52  110 2001-10-01  red
52  110 2001-10-01  red
52  -1  2001-10-01  red
52  -1  2001-10-01  red
Sign up to request clarification or add additional context in comments.

3 Comments

I did it the same just few minutes ago, but I've got a another problem. I'd like to get also ID from higher level (I mean 52 in this case), it should looks like: 110 52 2001-10-01 red 110 52 2001-10-01 red 110 52 2001-10-01 red -1 52 2001-10-01 red -1 52 2001-10-01 red
Do you have an idea how to achieve this? I've edited my post. Thanks for help!
If you JSON will not have more than 1 datapart you can simply add JSON_VALUE(@json,N'$.ID')

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.