鉴于下面的示例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
答案 0 :(得分:3)
一种可能的方法是使用OPENJSON()
和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
输出:
Id Type Employee
1 Submit Joe
1 Review Betty
1 Approve Sam
1 Approve Bill