更新 SQL 中的 JSON 数组属性

huangapple go评论56阅读模式
英文:

Updating JSON Array Property In SQL

问题

我正在使用Microsoft SQL Server,并且我有一个包含JSON数组的SQL变量。现在,我想要更新JSON数组中所有JSON对象的一个属性并将其设置为0。

我已经尝试了以下查询,但它只更新了第一个JSON对象。

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;

我知道我可以添加另一个语句,像这样:

SET @updatedJson = JSON_MODIFY(@updatedJson, '$1.MTML', 0);

到上面的查询,并更新第二个JSON对象。但我想看到一些通用的方法来做到这一点,而不是针对特定的数组元素。

非常感谢任何帮助!

英文:

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

得分: 1

你可以使用 OPENJSON 解析 JSON 文本并将 JSON 输入中的对象和属性返回为行和列,然后使用 JSON_MODIFY 单独更新每个对象,最后使用 STRING_AGG 构建更新后的 JSON。

SELECT @updatedJson = CONCAT('[', STRING_AGG(JSON_MODIFY([value], '$.MTML', 0), ',') WITHIN GROUP (ORDER BY CONVERT(int, [key])), ']') 
FROM OPENJSON(@Json);

演示在此

英文:

You can do it using OPENJSON that parses JSON text and returns objects and properties from the JSON input as rows and columns and JSON_MODIFY to update each object individually, then STRING_AGG to build the updated JSON

SELECT @updatedJson = CONCAT('[', STRING_AGG(JSON_MODIFY([value], '$.MTML', 0), ',') WITHIN GROUP (ORDER BY CONVERT(int, [key])), ']') 
FROM OPENJSON(@Json);

Demo here

huangapple
  • 本文由 发表于 2023年4月10日 19:26:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976667.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定