Insert an object into a JSON array in SQL Server

前端 未结 1 1186
刺人心
刺人心 2021-02-14 06:38

Every example that I\'ve seen for JSON_MODIFY shows inserting a simple value such as a string into an array.

Suppose I have the following JSON

1条回答
  •  别跟我提以往
    2021-02-14 07:09

    You should wrap the third parameter of your JSON_MODIFY statement with JSON_QUERY():

    UPDATE TheTable 
    SET TheJSON = JSON_MODIFY(TheJSON, 'append $', JSON_QUERY(N'{"id": 3, "name": "Three"}')) 
    WHERE Condition = 1;
    

    Here is a complete sample:

    DECLARE @TheTable table(TheJSON nvarchar(max), Condition int )
    DECLARE @mystring nvarchar(100)='{"id": 3, "name": "Three"}'
    
    INSERT INTO @TheTable SELECT '[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"}]', 1
    
    UPDATE @TheTable 
    SET TheJSON = JSON_MODIFY(TheJSON, 'append $', JSON_QUERY(N'{"id": 3, "name": "Three"}')) 
    WHERE Condition = 1;
    
    SELECT TheJSON FROM @TheTable
    

    This is the final output:

    [{"id": 1, "name": "One"}, {"id": 2, "name": "Two"},{"id": 3, "name": "Three"}]
    

    More info on JSON_QUERY here, and the explation of the issue is here.

    0 讨论(0)
提交回复
热议问题