【问题标题】:Trying to figure out syntax for OPENJSON query and stuck试图找出 OPENJSON 查询的语法并卡住了
【发布时间】:2021-10-14 10:53:12
【问题描述】:

我一直在非常努力地从我试图加载到某些表中的 JSON 消息中提取数据。我可以让这个在它上面有一个名称/值对的消息工作,但另一条消息有第二个外部名称/值对。

DECLARE @json nvarchar(max) =
'{
"request":
    {
    "requestId" : "3a282d32-4ed4-48e8-a6c0-23cf4921737e",
    "modelType" : "NEW"
    }
}'

select 'request' as title, request.requestId , request.modelType
from openjson(@json)
with
(
   request nvarchar(max) as json 
)
as Projects
cross apply openjson (Projects.request)
with
(
    requestId nvarchar(50),
    modelType nvarchar(50)
)  as request

这会按预期返回行,但是如果上面有额外的名称/值对,我该如何编写查询?像这样:

DECLARE @json nvarchar(max) =
'{
  "request": {
            "request":
                    {
                    "requestId" : "3a282d32-4ed4-48e8-a6c0-23cf4921737e",
                    "modelType" : "NEW"
                    }
            }   
}'

谁能帮忙。我知道这可能真的很简单,但我似乎无法理解如何去做。我是公司中唯一使用 JSON 的人,否则我会直接问他们。

提前谢谢你!

【问题讨论】:

    标签: sql json open-json


    【解决方案1】:

    还需要一个cross apply 才能达到目标。

    select 'request' as title, request.requestId , request.modelType
    from openjson(@json)
    with
    (
       request nvarchar(max) as json 
    )
    as Projects
    cross apply openjson (Projects.request)
    with
    (
        request nvarchar(max) as json 
    )  as subrequest
    cross apply openjson (subrequest.request)
    with
    (
        requestId nvarchar(50),
        modelType nvarchar(50)
    )  as request
    

    db<>fiddle中的演示

    【讨论】:

    • 就是这样!现在我不知道我在做什么,但我在修补时看起来和你的非常相似,但就是这样!为什么这对我来说如此困难,我永远无法理解。我想我可能一直在尝试在错误的位置使用 CROSS APPLY 作为第二个价值对
    猜你喜欢
    • 2020-09-24
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多