I have a table with following fields
Id RequestId CategoryId
1 112 1
2 123 1
3 123 2
SELECT R.RequestId,
(SELECT RC.CategoryId FROM Request RC WHERE RC.Id = R.Id FOR JSON AUTO) AS Categories
FROM Request R
Above query returns the data as mentioned below
RequestId Categories
112 [{"CategoryId":"1"}]
123 [{"CategoryId":"1"},{"CategoryId":"2"}]
But, I want that column name CategoryId should not be repeated for every item in json array. Thus, my expected result is:
RequestId Categories
112 ["1"]
123 ["1","2"]
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).
OPENJSON() function parses JSON in SQL Server In this context, the conversion of the JSON data into the relational format is becoming more important. OPENJSON is a table-valued function that helps to parse JSON in SQL Server and it returns the data values and types of the JSON text in a table format.
USE db_name; DESCRIBE table_name; it'll give you column names with the type.
Format query results as JSON, or export data from SQL Server as JSON, by adding the FOR JSON clause to a SELECT statement. Use the FOR JSON clause to simplify client applications by delegating the formatting of JSON output from the app to SQL Server.
Was used: SQL to JSON - array of objects to array of values in SQL 2016
create table Request ( Id int, RequestId int, CategoryId int ) GO
insert into Request (Id,RequestId,CategoryId) values ( 1, 112, 1), ( 2, 123, 1), ( 3, 123, 2); GO
SELECT distinct R.RequestId, ( SELECT JSON_QUERY('[' + STUFF(( SELECT ',' + '"' + convert(varchar(10), RC.CategoryId) + '"' FROM Request RC WHERE RC.RequestId = R.RequestId FOR XML PATH('')),1,1,'') + ']' ) Categories FOR JSON PATH , WITHOUT_ARRAY_WRAPPER ) AS Categories FROM Request R GO
RequestId | Categories --------: | :----------------------- 112 | {"Categories":["1"]} 123 | {"Categories":["1","2"]}
SELECT distinct R.RequestId, JSON_QUERY( ( SELECT JSON_QUERY('[' + STUFF(( SELECT ',' + '"' + convert(varchar(10), RC.CategoryId) + '"' FROM Request RC WHERE RC.RequestId = R.RequestId FOR XML PATH('')),1,1,'') + ']' ) Categories FOR JSON PATH , WITHOUT_ARRAY_WRAPPER ) , '$.Categories' ) FROM Request R GO
RequestId | (No column name) --------: | :--------------- 112 | ["1"] 123 | ["1","2"]
db<>fiddle here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With