5

给定下面的示例 json 数据,我如何编写一个查询来一步提取数组数据?我的目标是为 ActionRecs 数组 (4) 中的每个项目保留一行。我的实际 json 更复杂,但我认为这很好地说明了我的目标。

declare @json2 nvarchar(max)
set @json2 = '{
    "RequestId": "1",
    "ActionRecs": [
        {
            "Type": "Submit",
            "Employee": "Joe"
        },
        {
            "Type": "Review",
            "Employee": "Betty"
        },
        {
            "Type": "Approve",
            "Employee": "Sam"
        },
        {
            "Type": "Approve",
            "Employee": "Bill"
        }
    ]
}'

SELECT x.*
, JSON_QUERY(@json2, '$.ActionRecs') as ActionArray
from OPENJSON(@json2) 
with (Id varchar(5) '$.RequestId') as x

查询结果

4

1 回答 1

13

一种可能的方法是使用OPENJSON()显式模式和附加CROSS APPLY运算符:

DECLARE @json nvarchar(max)
SET @json = N'{
    "RequestId": "1",
    "ActionRecs": [
        {"Type": "Submit", "Employee": "Joe"},
        {"Type": "Review", "Employee": "Betty"},
        {"Type": "Approve", "Employee": "Sam"},
        {"Type": "Approve", "Employee": "Bill"}
    ]
}'

SELECT i.Id, a.[Type], a.[Employee]
FROM OPENJSON(@json) WITH (
   Id varchar(5) '$.RequestId',
   ActionRecs nvarchar(max) '$.ActionRecs' AS JSON
) AS i
CROSS APPLY OPENJSON(i.ActionRecs) WITH (
   [Type] nvarchar(max) '$.Type',
   [Employee] nvarchar(max) '$.Employee'
) a

输出:

Id  Type    Employee
1   Submit  Joe
1   Review  Betty
1   Approve Sam
1   Approve Bill
于 2019-01-25T19:02:10.283 回答