pre*_*elb 2 sql-server json json-query
给定下面的示例 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
Run Code Online (Sandbox Code Playgroud)
一种可能的方法是使用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
Run Code Online (Sandbox Code Playgroud)
输出:
Id Type Employee
1 Submit Joe
1 Review Betty
1 Approve Sam
1 Approve Bill
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8327 次 |
| 最近记录: |