SQL Server 查询结果转JSON函数

SQL Server SELECT to JSON function

http://stackoverflow.com/questions/6818441/sql-server-select-to-json-function


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

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, '') + ']'

Output:

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

posted on 2014-09-28 10:12  omage  阅读(76)  评论(0编辑  收藏  举报