将JSON节点转换为要选择的列

时间:2019-07-12 06:55:02

标签: json sql-server tsql

请参考这种情况:

DECLARE @Table AS TABLE (ID INT IDENTITY, Status VARCHAR(100), List VARCHAR(MAX))

INSERT INTO @Table (Status, List) 
VALUES ('Active', '[{"Header":"H1","Detail":"D1"}]')

SELECT * 
FROM @Table

这将返回输出

ID          Status             List    
------------------------------------------------                                                                                         
1           Active    [{"Header":"H1","Detail":"D1"}]

是否有一种方法可以将JSON节点提取为列以获取以下输出

ID          Status             Header        Detail
------------------------------------------------------                                                                                       
1           Active             H1              D1

1 个答案:

答案 0 :(得分:2)

您可以尝试使用其他APPLY运算符和OPENJSON使用明确的架构定义:

表格:

DECLARE @Table AS TABLE (ID INT IDENTITY,Status VARCHAR(100),List VARCHAR(MAX))
INSERT INTO @Table(Status,List) VALUES ('Active','[{"Header":"H1","Detail":"D1"}]')

声明:

SELECT t.ID, t.Status, j.Header, j.Detail
FROM @Table t
CROSS APPLY OPENJSON(List) WITH (
   Header nvarchar(2) '$.Header',
   Detail nvarchar(2) '$.Detail'
) j

输出:

ID  Status  Header  Detail
1   Active  H1      D1