1

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

 {
   "S": [
    {
      "Name": "Project1",
       "SP": [
        {
          "ID": 1,
          "Name": "Test1"
        },
        {
          "ID": 2,
          "Name": "Test2"
        },
  }]}

如何查询以获取 SP 值。

Expected Result:

 ID    Name 
 1     Test1 
 2     Test2

 I tried the below but not working. Can you please suggest the correct query.

SELECT DISTINCT JSON_VALUE(JsonData, '$.S[0].SP.ID') AS ID,
                JSON_VALUE(JsonData, '$.S[0].SP.Name') AS Name
    FROM TableA
4

1 回答 1

0

您可以使用包含子句的JSON_QUERY嵌套OPENJSON函数来动态访问数组WITH的所有成员:SP

SELECT ID, Name
  FROM TableA
 CROSS APPLY OPENJSON(JSON_QUERY(JsonData, '$.S[0].SP'))
             WITH (ID   nvarchar(500) '$.ID',
                   Name nvarchar(500) '$.Name')

顺便说一句,您需要将 JsonData 修复为转换为

{
   "S": [
    {
      "Name": "0219 Project Methodology - Allergies",
       "SP": [
        {
          "ID": 1,
          "Name": "Test1"
        },
        {
          "ID": 2,
          "Name": "Test2"
        }
  ] } ] }

Demo

于 2020-04-14T09:00:40.353 回答