[英]Using cross apply to query nested arrays in json
我有一个可能相对简单的查询,但我无法理解如何查询嵌套的 json 数组。 我有一个带有 json 字段的 SQL 2016 DB,其中包含一个带有多个子数组的 json 字符串。
附上一张json数据的图片:
我要查询“身份”数据(99999829250103)
我可以使用以下查询查询诸如 accountId (LOADACC001) 或昵称 (LoadTest) 之类的数据,但无法从“account”数组进行查询:
SELECT top 1
accountId as NonUserAccountId
FROM [DBName].DBSchema.transactions t
CROSS APPLY OPENJSON (t.BankDataText, N'$.data')
WITH
(
accountId VARCHAR(100) 'strict $.account.accountId'
)
where t.Id = 675
字段 'BankDataText' 包含 json 字符串,该表称为 'transactions'。 当我向查询添加另一个 CROSS APPLY 时,没有返回任何行。
您在正确的轨道上,您只需要使用as json
提取嵌套的 json 部分,然后使用另一个cross apply
与open json
来读取内部account
部分:
declare @tmp table ([id] int, BankDataText nvarchar(max))
declare @j nvarchar(max)='{
"data": [{
"account": {
"account": [{
"schemaName": "SortCodeAccountNumber",
"identification": "99999829250103",
"name": "Load testing ....",
"secondaryIdentification": "123456789"
}],
"accountType": "null",
"accountSubType": "null",
"description": null,
"accountId": "LOADACC001",
"currency": "GBP",
"nickname": "LoadTest",
"servicer": {
"schemaName": "BICFI",
"identification": "PAPAUK00XXX"
}
}
}]
}'
insert into @tmp select 675, @j
select top 1
A.accountId as NonUserAccountId, B.identification
from @tmp t
cross apply openjson (t.BankDataText, N'$.data') with
(
accountId varchar(100) 'strict $.account.accountId',
account nvarchar(max) 'strict $.account.account' as json
) A
cross apply openjson(A.account) with
(
identification varchar(100)
) B
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.