简体   繁体   English

使用交叉应用查询json中的嵌套数组

[英]Using cross apply to query nested arrays in json

I have what is probably a relatively easy query but I cannot get my head around how to query nested json arrays.我有一个可能相对简单的查询,但我无法理解如何查询嵌套的 json 数组。 I have a SQL 2016 DB with a json field which contains a json string with multiple child arrays.我有一个带有 json 字段的 SQL 2016 DB,其中包含一个带有多个子数组的 json 字符串。

Attached is an image of the json data:附上一张json数据的图片:

在此处输入图片说明

I would like to query the "identification" data (99999829250103)我要查询“身份”数据(99999829250103)

I can query data such as the accountId (LOADACC001) or nickname (LoadTest) using the following query but cannot query from the "account" array:我可以使用以下查询查询诸如 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

The field 'BankDataText' contains the json string and the table is called 'transactions'.字段 'BankDataText' 包含 json 字符串,该表称为 'transactions'。 when I add another CROSS APPLY to the query no rows are returned.当我向查询添加另一个 CROSS APPLY 时,没有返回任何行。

You are on the right track, you just need to extract the nested json section with as json and then use another cross apply with open json to read the inner account section:您在正确的轨道上,您只需要使用as json提取嵌套的 json 部分,然后使用另一个cross applyopen 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

Result:结果:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM