JSON Nested Object to SQL Server Stored Procedure

五迷三道 提交于 2021-01-28 09:00:51

问题


I am trying to insert multiple rows from a single JSON object, where each row is the n'th name/value pair in the JSON nested-object

Here is what the SQL Server table looks like:

ID | Name | Value |

Here is what the JSON looks like:

{
   "PropData":{ 
    "Name1": "Value1",
    "Name2": "Value2",
    "Name3": "Value3"       
    }
}

Here is what I have so far for the stored procedure (ID is static and should be the same for each row - I've left out how that is retrieved for brevity as it isn't relevant to the question).

CREATE PROCEDURE usp.InsertPropData
    @jsonProps NVARCHAR(MAX)
AS
BEGIN 
    SET @ID = (SELECT ID FROM MyOtherTable);

 BEGIN TRANSACTION
     INSERT INTO Prop_Table(ID, Name, Value)
         SELECT @ID, Name, Value
         FROM OPENJSON(@jsonProps)
              WITH(Name VARCHAR(500), Value VARCHAR(500))
     COMMIT TRANSACTION
END

The issue is that it's failing to find Name and Value in the JSON read.. I think I need to somehow tell it to look at the PropData nested object and parse the name/value from that? But I do not know how to tell SQL to do that.

Here is what the table should look like after successful execution of the stored procedure in this example:

ID | Name | Value |
---+------+-------+
1  |Name1 | Value1|
1  |Name2 | Value2|
1  |Name3 | Value3|

回答1:


Using OPENJSON and passing a path to it should work fine.

DECLARE @JSON NVARCHAR(4000) = '{
   "PropData":{ 
    "Name1": "Value1",
    "Name2": "Value2",
    "Name3": "Value3"       
    }
}'


SELECT [key], [value]
FROM OPENJSON(@json, '$.PropData')


来源:https://stackoverflow.com/questions/52297060/json-nested-object-to-sql-server-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!