I am using Microsoft SQL server, and I have a variable in SQL that contains a JSON array. Now, I am trying to update one property and set it to 0 for all the JSON objects inside the JSON array.
I have tried the following query, but it just updates the first JSON object.
DECLARE @Json varchar(MAX), @updatedJson varchar(MAX);
SET @Json ='[{"LocationID":1234,"LocationName":"ABCD","MTML":1},{"LocationID":12345,"LocationName":"LMNO","MTML":3}]'
SET @updatedJson = JSON_MODIFY(@Json, '$[0].MTML', 0);
SELECT @updatedJson;
I know that I can add one more statement like:
SET @updatedJson = JSON_MODIFY(@updatedJson, '$[1].MTML', 0);
to the above query and update the second JSON object. But I would like to see some suggestions to do this in a generic way and not for specific array elements.
Would highly appreciate any help!
1条答案
按热度按时间kiayqfof1#
You can do it using
OPENJSON
that parses JSON text and returns objects and properties from the JSON input as rows and columns andJSON_MODIFY
to update each object individually, thenSTRING_AGG
to build the updated JSONDemo here