如何在子OPENJSON的结果上使用OPENJSON

时间:2016-11-07 20:55:47

标签: json tsql sql-server-2016

我有一个像这样的JSON结构:

Declare @layout NVARCHAR(MAX) = N'
    {
        "Sections": [
            {
                "SectionName":"Section1",
                "SectionOrder":1,
                "Fields":[
                    {
                        "FieldName":"Field1",
                        "FieldData":"Data1"
                    },
                    {
                        "FieldName":"Field2",
                        "FieldData":"Data2"
                    }
                ]
            },
            {
                "SectionName":"Section2",
                "SectionOrder":2,
                "Fields":[
                    {
                        "FieldName":"Field3",
                        "FieldData":"Data3"
                    },
                    {
                        "FieldName":"Field4",
                        "FieldData":"Data4"
                    }
                ]
            }
        ]
    }
'

如何查询相应的Sections.Fields.FieldName =' Field3'?

select *
from OPENJSON(@layout,'$.Sections') 
WITH (
    SectionName nvarchar(MAX) '$.SectionName',  
    SectionOrder nvarchar(MAX) '$.SectionOrder', 
    Fields nvarchar(MAX) '$.Fields' as JSON
)

据我所知,我不能再进一步下去,否则不会有任何结果。

1 个答案:

答案 0 :(得分:1)

阅读文档后想出来,完全有效!

SELECT SectionName, FieldName, FieldData FROM (
    select *
    from OPENJSON(@layout,'$.Sections') 
    WITH (
        SectionName nvarchar(MAX) '$.SectionName',  
        SectionOrder nvarchar(MAX) '$.SectionOrder', 
        Fields nvarchar(MAX) '$.Fields' as JSON
    )
) as Sections
CROSS APPLY OPENJSON(Fields,'$')
WITH (
    FieldName nvarchar(MAX) '$.FieldName',  
    FieldData nvarchar(MAX) '$.FieldData'
)