我有一个JSON结构,其中有章节,由多个渲染器组成,由多个字段组成。
如何在最低层(字段)上调用1 OPENJSON以获取所有信息?
下面是一个JSON示例:
Declare @layout NVARCHAR(MAX) = N'
{
"Sections": [
{
"SectionName":"Section1",
"SectionOrder":1,
"Renders":[
{
"RenderName":"Render1",
"RenderOrder":1,
"Fields":[
{
"FieldName":"Field1",
"FieldData":"Data1"
},
{
"FieldName":"Field2",
"FieldData":"Data2"
}
]
},
{
"RenderName":"Render2",
"RenderOrder":2,
"Fields":[
{
"FieldName":"Field1",
"FieldData":"Data1"
},
{
"FieldName":"Field2",
"FieldData":"Data2"
}
]
}
]
},
{
"SectionName":"Section2",
"SectionOrder":2,
"Renders":[
{
"RenderName":"Render1",
"RenderOrder":1,
"Fields":[
{
"FieldName":"Field1",
"FieldData":"Data1"
}
]
},
{
"RenderName":"Render2",
"RenderOrder":2,
"Fields":[
{
"FieldName":"Field1",
"FieldData":"Data1"
},
{
"FieldName":"Field2",
"FieldData":"Data2"
}
]
}
]
}
]
}
'
下面是一些嵌套OPENJSON调用的代码示例,它可以工作,但非常复杂,不能动态生成,我如何使它成为一个级别的调用?
SELECT SectionName, SectionOrder, RenderName, RenderOrder, FieldName, FieldData FROM (
SELECT SectionName, SectionOrder, RenderName, RenderOrder, Fields FROM (
select SectionName, SectionOrder, Renders
from OPENJSON(@layout,'$.Sections')
WITH (
SectionName nvarchar(MAX) '$.SectionName',
SectionOrder nvarchar(MAX) '$.SectionOrder',
Renders nvarchar(MAX) '$.Renders' as JSON
)
) as Sections
CROSS APPLY OPENJSON(Renders,'$')
WITH (
RenderName nvarchar(MAX) '$.RenderName',
RenderOrder nvarchar(MAX) '$.RenderOrder',
Fields nvarchar(MAX) '$.Fields' as JSON
)
) as Renders
CROSS APPLY OPENJSON(Fields,'$')
WITH (
FieldName nvarchar(MAX) '$.FieldName',
FieldData nvarchar(MAX) '$.FieldData'
)
这就是我想要实现的:
select FieldName, FieldData
from OPENJSON(@layout,'$.Sections.Renders.Fields')
WITH (
FieldName nvarchar(MAX) '$.Sections.Renders.Fields.FieldName',
FieldData nvarchar(MAX) '$.Sections.Renders.Fields.FieldData'
)
4条答案
按热度按时间hec6srdp1#
每个问题的答案列表样本
JSON样本
kpbpu0082#
我有JSON代码并插入到名为MstJson的表中,包含JSON代码的列名就是JSON数据。JSON代码:
使用CrossApply(嵌套数组)的OpenJson SQL代码:
o0lyfsai3#
虽然你不能只使用一个OPENJSON,但你可以通过删除嵌套的子查询来简化查询,使其更容易动态创建:
如果您有一个基元数组,则可以在将嵌套数组公开为JSON字段后使用
value
属性访问数据。使用下面注解中的JSON,您可以从原始数组中获取值:osh3o9ms4#
这可以通过CROSS将JSON子节点与父节点一起应用,并使用JSON_Value()函数来完成,如下所示: