Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server SELECT to JSON function

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!

For example, the below table Users

id    name        active 1     Bob Jones   1 2     John Smith  0 

Would be returned like this:

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

Thanks in advance.

like image 346
jamesmhaley Avatar asked Jul 25 '11 15:07

jamesmhaley


People also ask

How pass JSON data in SQL Server?

There is no json data type in SQL Server you can simply send your json as nvarchar(max) to a stored procedure. If you want to map your json to table you can use use OPENJSON to convert data to rows and columns.

What is JSON extract () function in MySQL?

We can use the JSON_EXTRACT function to extract data from a JSON field. The basic syntax is: JSON_EXTRACT(json_doc, path) For a JSON array, the path is specified with $[index] , where the index starts from 0: mysql> SELECT JSON_EXTRACT('[10, 20, 30, 40]', '$[0]'); +------------------------------------------+


2 Answers

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 

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

Output:

[{"id":1,"name":"Bob Jones","active":1},{"id":2,"name":"John Smith","active":0}] 
like image 60
Kirill Polishchuk Avatar answered Sep 20 '22 13:09

Kirill Polishchuk


Just for improving answer with latest technology change. with sql server 2016

select id, name ,active      from  tableName        FOR JSON AUTO 
like image 44
Amrik Avatar answered Sep 20 '22 13:09

Amrik