T-SQL 使用 FOR JSON PATH 检索数组等部分数据

T-SQL to retrieve part of data such as array using FOR JSON PATH

我正在尝试以特定方式从我们的 SQL 服务器检索数据,基本上我有一个列,它有一个分隔符 ',' 并且需要像数组一样使用 FOR JSON路径

我已经尝试使用 FOR XML PATH 和 FOR JSON PATH,但我不知道如何克服这个查询。

除此之外,我还有其他方法可以解决,使用 Entity Framework + LINQ 进行映射,我需要修复或了解在 SQL SERVER 中是否可行。

这是我没有 FOR JSON:

的简单数据

这就是我正在做的事情:

select * from #templateData FOR JSON PATH

-- result
[
    {
        "id": 1,
        "name": "Full Stack Engineer",
        "description": ".net developer with 20 year of experience,Scrum master,Hold bachelor degree "
    },
    {
        "id": 2,
        "name": "Web Developer",
        "description": "web dev"
    },
    {
        "id": 3,
        "name": "Full Stack Engineer",
        "description": "tested"
    }
]

这就是我所期待的(见列描述)

[
    {
        "id": 1,
        "name": "Full Stack Engineer",
        "description": [
                         {".net developer with 20 year of experience"},
                         {"Scrum master"},
                         {"Hold a bachelor degree"},
                       ],
    },
    {
        "id": 2,
        "name": "Web Developer",
        "description": "web dev"
    },
    {
        "id": 3,
        "name": "Full Stack Engineer",
        "description": "tested"
    }
]

我尝试过使用 STRING_SPLITFOR JSON PATH 一起使用 CROSS_APPLY,但是没有成功。

抱歉,我之前发表了错误的评论并已将其删除。我想你想要这样的东西。

[编辑]:现在它使用框架拆分器。

declare @json           nvarchar(max)=N'[
    {
        "id": 1,
        "name": "Full Stack Engineer",
        "description": ".net developer with 20 year of experience,Scrum master,Hold bachelor degree "
    },
    {
        "id": 2,
        "name": "Web Developer",
        "description": "web dev"
    },
    {
        "id": 3,
        "name": "Full Stack Engineer",
        "description": "tested"
    }
]'

;with j_cte(id, [name], [description]) as (
    select * from openjson(@json) with (id               int,
                                        [name]           nvarchar(200),
                                        [description]    nvarchar(4000)))
select id, [name],
    (select [value] from string_split(j.[description], ',') for json path) [description]
from j_cte j for json path;

产生输出:

[
  {
    "id": 1,
    "name": "Full Stack Engineer",
    "description": [
      {
        "Item": ".net developer with 20 year of experience"
      },
      {
        "Item": "Scrum master"
      },
      {
        "Item": "Hold bachelor degree "
      }
    ]
  },
  {
    "id": 2,
    "name": "Web Developer",
    "description": [
      {
        "Item": "web dev"
      }
    ]
  },
  {
    "id": 3,
    "name": "Full Stack Engineer",
    "description": [
      {
        "Item": "tested"
      }
    ]
  }
]