SQL Server SELECT 到 JSON 函数 [英] SQL Server SELECT to JSON function

查看:43
本文介绍了SQL Server SELECT 到 JSON 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 SELECT 语句的结果作为 JSON 对象输出.

I would like to output the results of a SELECT statement as a JSON object.

我希望这是一个函数而不是一个存储过程

I would like this to be a Function and not a stored procedure!

例如下表用户

id    name        active
1     Bob Jones   1
2     John Smith  0

会像这样返回:

[{"id":1,"name":"Bob Jones","active":1},{"id":2,"name":"John Smith","active":0}]

提前致谢.

推荐答案

从 SQL Server 2016 开始,您可以使用 for json:

Starting from SQL Server 2016 you can use for json:

declare @t table(id int, name nvarchar(max), active bit)
insert @t values (1, 'Bob Jones', 1), (2, 'John Smith', 0)

select id, name, active
from @t
for json auto

对于旧版本的 SQL Server,您可以使用 for xml path,例如:

With older versions of SQL Server you can use for xml path, e.g.:

select '[' + STUFF((
        select 
            ',{"id":' + cast(id as varchar(max))
            + ',"name":"' + name + '"'
            + ',"active":' + cast(active as varchar(max))
            +'}'

        from @t t1
        for xml path(''), type
    ).value('.', 'varchar(max)'), 1, 1, '') + ']'

输出:

[{"id":1,"name":"Bob Jones","active":1},{"id":2,"name":"John Smith","active":0}]

这篇关于SQL Server SELECT 到 JSON 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆