【问题标题】:How to get json string along columns in SQL Server如何沿 SQL Server 中的列获取 json 字符串
【发布时间】:2020-11-20 09:36:13
【问题描述】:

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

表:员工

id  | name | sal | depno
----+------+-----+------
1   | a    | 100 | 10
2   | b    | 200 | 20

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

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}

我试过这个查询:

select * 
from emp 
for json path, include_null_values, without_array_wrapper 

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

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

【问题讨论】:

  • SQL Server 2012 不支持FOR JSON。您需要将您的实例升级到可以支持的 SQL Server 版本(SQL Server 2016+)。
  • 这能回答你的问题吗? How to make JSON from SQL query in MS SQL 2014(请注意,虽然这说明 2014 年,但答案将起作用,因为 2014 年的大部分功能与 Azure 相关并且新的基数估计器。没有像 2016 年及以后那样的新功能)

标签: sql json sql-server sql-server-2012 sql-server-2016


【解决方案1】:

如果您使用的是 SQL Server 2016+(内置 JSON 支持),您只需为每一行提供FOR JSON PATH

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)

结果:

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}

【讨论】:

    猜你喜欢
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    相关资源
    最近更新 更多