0

我有下面的 Json 字符串。我需要编写一个查询来获取 TP 记录。在不提供索引值的情况下,我们需要得到结果。

{
   "S": [
    {
      "Name": "Project1",
      "SP": [
       {
          "ID": 1,
          "Name": "Test1",
          "TP": [
            {
              "TID": 11,
              "TName": "TT1",
            },
            {
              "TID": 12,
              "TName": "TT2",
            },
         ]
      },
      {
        "ID": 2,
        "Name": "Test2",
        "TP": [
         {
          "TID": 13,
          "TName": "TT3",
         },
         {
          "TID": 14,
          "TName": "TT4",
         },
       ]
    },
  ]}]}

如何查询以获取 TP 值。

预期结果:

  TID    TName 
  11     TT1 
  12     TT2
  13     TT3
  14     TT4
4

1 回答 1

1

您可以使用OPENJSON包含WITH子句的函数添加尽可能多的CROSS APPLY子句来查看所有子数组:

SELECT S3.TID, S3.TName
  FROM tab
 CROSS APPLY OPENJSON(JsonData)
             WITH ( S  nvarchar(max) '$.S' AS JSON) AS S0
 CROSS APPLY OPENJSON (S0.S) 
             WITH (
                    SP nvarchar(max) '$.SP' AS JSON ) S1
 CROSS APPLY OPENJSON (S1.SP) 
             WITH (
                    TP nvarchar(max) '$.TP' AS JSON ) S2
 CROSS APPLY OPENJSON (S2.TP) 
             WITH (
                    TID   nvarchar(500) '$.TID', 
                    TName nvarchar(500) '$.TName' ) S3

Demo

更新:如果第一个数组S被固定为只包含一个项目,我们可以减少一步为

SELECT S3.TID, S3.TName
  FROM tab
 CROSS APPLY OPENJSON(JsonData)
             WITH (
                    SP nvarchar(max) '$.S[0].SP' AS JSON ) S1
 CROSS APPLY OPENJSON (S1.SP) 
             WITH (
                    TP nvarchar(max) '$.TP' AS JSON ) S2
 CROSS APPLY OPENJSON (S2.TP) 
             WITH (
                    TID   nvarchar(500) '$.TID', 
                    TName nvarchar(500) '$.TName' ) S3  

Demo

于 2020-04-17T10:50:07.433 回答