Reading json array into rows in SQL Server

南楼画角 提交于 2020-07-02 02:01:12

问题


Given the sample json data below, how can I write a query to pull the array data all in one step? My goal is to have one row for each item in the ActionRecs array (4). My actual json is more complicated but I think this gives a good example of my goal.

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


回答1:


One possible approach is to use OPENJSON()and CROSS APPLY:

DECLARE @json nvarchar(max)
SET @json = '{
    "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',
   Actions nvarchar(max) '$.ActionRecs' AS JSON
) AS i
CROSS APPLY (
   SELECT *
   FROM OPENJSON(i.Actions)
   WITH (
      [Type] nvarchar(max) '$.Type',
      [Employee] nvarchar(max) '$.Employee'
   )
) a

Output:

Id  Type    Employee
1   Submit  Joe
1   Review  Betty
1   Approve Sam
1   Approve Bill


来源:https://stackoverflow.com/questions/54371192/reading-json-array-into-rows-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!