MS SQL Json 数组处理与单独的数组

MS SQL Json array processing with separate arrays

我对 JSON 数据以及如何在 SQL table 中获取数据有疑问,所以数据是:

[
   {
      "id":"1121131",
      "idGroups":[
         "123",
         "X999"
      ],
      "idGroupNames":[
         "Neutral",
         "Service"
      ]
   },
   {
      "id":"2233154",
      "idGroups":[
         "654321"
      ],
      "idGroupNames":[
         "Position"
      ]
   }
]

所需的输出是

Id idGroups idGroupNames
1121131 123 Neutral
1121131 X999 Service
2233154 654321 Position

我试图通过 OPENJSON()CROSS APPLY 获得想要的结果,但我认为我没有取得任何进展。

我最初的尝试是

DECLARE @json NVARCHAR(MAX) = N'[
   {
      "id":"1121131",
      "idGroups":[
         "123",
         "X999"
      ],
      "idGroupNames":[
         "Neutral",
         "Service"
      ]
   },
   {
      "id":"2233154",
      "idGroups":[
         "654321"
      ],
      "idGroupNames":[
         "Position"
      ]
   }
]'
SELECT id,idGroup,idGroupName FROM OPENJSON (@json)
WITH (
    id INT 'strict $.id',
    idGroups NVARCHAR(MAX) '$.idGroups' AS JSON,
    idGroupNames NVARCHAR(MAX) '$.idGroupNames' AS JSON
    ) CROSS APPLY OPENJSON(idGroups)
    WITH (
        idGroup VARCHAR(500) '$'
    ) CROSS APPLY OPENJSON(idGroupNames)
    WITH (
        idGroupName VARCHAR(500) '$'
    )

您需要将 OPENJSON() 与默认架构和两个额外的 APPLY 运算符一起使用。以下语句是您问题的可能解决方案:

JSON:

DECLARE @json nvarchar(max) = N'[
   {
      "id":"1121131",
      "idGroups":[
         "123",
         "X999"
      ],
      "idGroupNames":[
         "Neutral",
         "Service"
      ]
   },
   {
      "id":"2233154",
      "idGroups":[
         "654321"
      ],
      "idGroupNames":[
         "Position"
      ]
   }
]'

声明:

SELECT j.id, j1.[value] AS idGroups, j2.[value] AS idGroupNames
FROM OPENJSON(@json) WITH (
   id nvarchar(7) '$.id',
   idGroups nvarchar(max) '$.idGroups' AS JSON,
   idGroupNames nvarchar(max) '$.idGroupNames' AS JSON
) j
CROSS APPLY OPENJSON(j.idGroups) j1
CROSS APPLY OPENJSON(j.idGroupNames) j2
WHERE j1.[key] = j2.[key]

您可以在没有第三个 OPENJSON 的情况下使用 JSON_VALUE 和动态路径。

这仅适用于 SQL Server 2017+

DECLARE @json nvarchar(max) = N'[
   {
      "id":"1121131",
      "idGroups":[
         "123",
         "X999"
      ],
      "idGroupNames":[
         "Neutral",
         "Service"
      ]
   },
   {
      "id":"2233154",
      "idGroups":[
         "654321"
      ],
      "idGroupNames":[
         "Position"
      ]
   }
]';

SELECT j.id, j1.[value] AS idGroups, JSON_VALUE(j.idGroupNames, '$[' + j1.[key] + ']') AS idGroupNames
FROM OPENJSON(@json) WITH (
   id nvarchar(7) '$.id',
   idGroups nvarchar(max) '$.idGroups' AS JSON,
   idGroupNames nvarchar(max) '$.idGroupNames' AS JSON
) j
CROSS APPLY OPENJSON(j.idGroups) j1;

db<>fiddle