[英]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.