如何使用 openjson 阅读存储在 SQL 服务器中的 Json 列下方?

How can I read below Json column stored in SQL Server using openjson?

Declare @ResponseText nvarchar(4000)

set @responseText ='{
    "submissions": [
        {
        "xml_id":"id_x5d94851726b470.68571510",
        "fields": [ 
            {"fieldvalue":"customerEmail@xyzdomain.com","fieldid":"57282490"},
            {"fieldvalue":"123","fieldid":"57282423"},
            {"fieldvalue":"12345-678900","fieldid":"57282500"}, 
            {"fieldvalue":"Test Message here ","fieldid":"57282564"}
         ]
         }
    ]
 }'

 SELECT  *
 FROM OPENJSON (@ResponseText, '$.submissions') WITH (
    ID NVARCHAR(100) '$.xml_id',
    $.fields.field NVARCHAR(100) ...
 )

等其他所有记录?我得到 "NULL" 字段数组

下的其余字段

你可以这样试试:

Declare @ResponseText nvarchar(4000)

set @responseText ='{
    "submissions": [
        {
        "xml_id":"id_x5d94851726b470.68571510",
        "fields": [ 
            {"fieldvalue":"customerEmail@xyzdomain.com","fieldid":"57282490"},
            {"fieldvalue":"123","fieldid":"57282423"},
            {"fieldvalue":"12345-678900","fieldid":"57282500"}, 
            {"fieldvalue":"Test Message here ","fieldid":"57282564"}
         ]
         }
    ]
 }'

--查询

 SELECT A.ID
       ,B.*
 FROM OPENJSON (@ResponseText, '$.submissions') 
      WITH (ID NVARCHAR(100) '$.xml_id'
           ,fields NVARCHAR(MAX) AS JSON) A
 OUTER APPLY OPENJSON(a.fields)
             WITH(fieldvalue NVARCHAR(150)
                 ,fieldid BIGINT) B;

结果

ID                          fieldvalue                  fieldid
id_x5d94851726b470.68571510 customerEmail@xyzdomain.com 57282490
id_x5d94851726b470.68571510 123                         57282423
id_x5d94851726b470.68571510 12345-678900                57282500
id_x5d94851726b470.68571510 Test Message here           57282564

简而言之:

您开始正确地使用 WITH 子句来阅读 xml_id。 属性 fields 只不过是同一级别的另一个元素。但是我们return它AS JSON。这将允许添加另一个 APPLY OPENJSON(),传入我们从 $.fields 获得的片段并使用另一个 WITH 子句来获取数组中对象的两个属性。