Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get multiple rows using FOR JSON clause

Using PostgreSQL I can have multiple rows of json objects.

select (select ROW_TO_JSON(_) from (select c.name, c.age) as _) as jsonresult from employee as c

This gives me this result:

{"age":65,"name":"NAME"}
{"age":21,"name":"SURNAME"}

But in SqlServer when I use the FOR JSON AUTO clause it gives me an array of json objects instead of multiple rows.

select c.name, c.age from customer c FOR JSON AUTO

[{"age":65,"name":"NAME"},{"age":21,"name":"SURNAME"}]

How to get the same result format in SqlServer ?

like image 707
izengod Avatar asked Apr 24 '17 11:04

izengod


People also ask

How can I get specific data from JSON?

Getting a specific property from a JSON response object Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.

How do I query JSON data in SQL?

To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function. For more information, see Convert JSON Data to Rows and Columns with OPENJSON (SQL Server).

What are {} in JSON?

JSON has the following syntax. Objects are enclosed in braces ( {} ), their name-value pairs are separated by a comma ( , ), and the name and value in a pair are separated by a colon ( : ). Names in an object are strings, whereas values may be of any of the seven value types, including another object or an array.


1 Answers

no structure better performance

SELECT c.id, jdata.*
FROM customer c
  cross apply 
    (SELECT * FROM customer jc where jc.id = c.id FOR JSON PATH , WITHOUT_ARRAY_WRAPPER) jdata (jdata)
like image 164
Barak Yellin Avatar answered Sep 18 '22 13:09

Barak Yellin