如何在 SQL Server 中获取沿列的 json 字符串

har*_*thu 1 sql sql-server json sql-server-2012 sql-server-2016

我有一个关于 SQL Server 的问题:如何使用几列获取 json 格式并获取列?

表:雇员

id  | name | sal | depno
----+------+-----+------
1   | a    | 100 | 10
2   | b    | 200 | 20
Run Code Online (Sandbox Code Playgroud)

根据这些数据,我想要这样的输出:

id  | name | sal  | deptno | empjsonstring
----+------+------+--------+-------------------------------------------
1   | a    | 100  | 10     | {"id":1,"name":"a","sal":100,"deptno":10}
2   | b    | 200  | 20     | {"id":2,"name":"b","sal"200,"deptno":20}
Run Code Online (Sandbox Code Playgroud)

我尝试过这个查询:

select * 
from emp 
for json path, include_null_values, without_array_wrapper 
Run Code Online (Sandbox Code Playgroud)

但这并没有返回预期的结果。

您能告诉我如何在 SQL Server 中编写查询来完成此任务吗?

Zho*_*rov 5

如果您使用的是 SQL Server 2016+(具有内置 JSON 支持),您只需FOR JSON PATH为每行构建 JSON 内容:

SELECT 
   id, name, sal, deptno,
   (SELECT id, name, sal, deptno FOR JSON PATH, WITHOUT_ARRAY_WRAPPER) AS empjsonstring
FROM (VALUES
   (1, 'a', 100, 10),
   (2, 'b', 200, 20)
) emp (id, name, sal, deptno)
Run Code Online (Sandbox Code Playgroud)

结果:

id  name    sal deptno  empjsonstring
1   a       100 10      {"id":1,"name":"a","sal":100,"deptno":10}
2   b       200 20      {"id":2,"name":"b","sal":200,"deptno":20}
Run Code Online (Sandbox Code Playgroud)