【问题标题】:Using cross apply to query nested arrays in json使用交叉应用查询json中的嵌套数组
【发布时间】:2019-01-02 13:24:27
【问题描述】:

我有一个可能相对简单的查询,但我无法理解如何查询嵌套的 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 时,不会返回任何行。

【问题讨论】:

  • 请以文本(非图像)格式发布整个 json

标签: sql json sql-server tsql sql-server-2016


【解决方案1】:

您在正确的轨道上,您只需要使用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

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 2018-05-20
    相关资源
    最近更新 更多