小编典典

SQL Server SELECT到JSON功能

json

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

我希望这是一个 功能, 而不是一个 存储过程

例如,下表Users

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}]

提前致谢。


阅读 396

收藏
2020-07-27

共1个答案

小编典典

从SQL Server 2016开始,您可以使用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,例如:

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}]
2020-07-27