Christopher
Christopher

Reputation: 788

JSON Nested Object to SQL Server Stored Procedure

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|

Upvotes: 1

Views: 3346

Answers (1)

dfundako
dfundako

Reputation: 8314

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')

Upvotes: 2

Related Questions