SQL-openjson从json提取密钥

时间:2018-08-14 16:12:22

标签: sql json sql-server tsql parsing

@json下面的一个数组中包含3个数据对象。使用OPENJSON将这些对象提取到Table变量后,请参见附带的输出。

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

输出

enter image description here

目标是将Key列中的json的Container列值替换为Data列中的所有三行的json属性值。

预期产量

enter image description here

注意:预期的输出是硬编码的,只显示一行,而所有行都需要相同。

1 个答案:

答案 0 :(得分:2)

您可以使用JSON_VALUE

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

DBFiddle Demo