简体   繁体   中英

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. I have a SQL 2016 DB with a json field which contains a json string with multiple child arrays.

Attached is an image of the json data:

在此处输入图片说明

I would like to query the "identification" data (99999829250103)

I can query data such as the accountId (LOADACC001) or nickname (LoadTest) using the following query but cannot query from the "account" array:

   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'. when I add another CROSS APPLY to the query no rows are returned.

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:

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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