【问题标题】:Reading json array into rows in SQL Server将 json 数组读入 SQL Server 中的行
【发布时间】:2019-01-25 18:46:27
【问题描述】:

鉴于下面的示例 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

【问题讨论】:

    标签: json sql-server json-query


    【解决方案1】:

    一种可能的方法是将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
    

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      相关资源
      最近更新 更多