Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

enter image description here

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.

like image 403
SilverE Avatar asked Sep 06 '25 13:09

SilverE


1 Answers

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:

enter image description here

like image 142
Andrea Avatar answered Sep 10 '25 18:09

Andrea