6

Below @json contains 3 data object within an array. After using OPENJSON to extract these objects to a Table variable, please see the output attached.

DECLARE @json NVARCHAR(MAX);  
SET @json = N'[{"Container":"MSKU2913236","Seal":"ML-TH4773979","Size":"20","Temperature":"-20","TareWeight":"3.132","CreatedDate":"02-02-2018 00:00:00","Comment":null,"NetWeight":"21.445","TempRec#":null},{"Container":"MSKU3432702","Seal":"ML-TH4773972","Size":"20","Temperature":"-40","TareWeight":"2.872","CreatedDate":"02-02-2018 00:00:00","Comment":null,"NetWeight":"23.932","TempRec#":"TR12345"},{"Container":"MSKU4043053","Seal":"ML-TH4773973","Size":"20","Temperature":"-20","TareWeight":"2.995","CreatedDate":"02-02-2018 00:00:00","Comment":null,"NetWeight":"22.4","TempRec#":null}]';

DECLARE @ContainerTable TABLE(
    [Key] NVARCHAR(100),
    [Data] NVARCHAR(MAX)
);

INSERT INTO @ContainerTable
SELECT [key], [value] FROM OPENJSON(@json)

SELECT * FROM @ContainerTable

Output

enter image description here

Objective is to replace the Key column values with the Container property value from json in the Data column for all 3 rows.

Expected Output

enter image description here

Note: Expected output is hard coded and it only shows the one row but same is required for all rows.

1
  • Resultset is not json, I am storing data in table and need to replace key with one of the property value of the json Commented Aug 14, 2018 at 16:17

1 Answer 1

6

You could use JSON_VALUE:

INSERT INTO @ContainerTable([Key], [Data])
SELECT JSON_VALUE([value],'$.Container'), [value]
FROM OPENJSON(@json);

DBFiddle Demo

Sign up to request clarification or add additional context in comments.

1 Comment

No need for the sub-select, this SELECT JSON_VALUE([value],'$.Container'), [value] FROM OPENJSON(@json) is enough...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.