I want to execute a select query on a table and I need this result in a JSON format. I want to do this using query only in SQL Server 2014.
My data is as follows.
DECLARE @Country TABLE (id INT, [CounrtyName] Varchar(30) )
INSERT INTO @Country VALUES (1,'India')
INSERT INTO @Country VALUES (1,'BAN')
INSERT INTO @Country VALUES (1,'USA')
INSERT INTO @Country VALUES (2,'Japan')
INSERT INTO @Country VALUES (2,'China')
INSERT INTO @Country VALUES (3,'Switzerland')
INSERT INTO @Country VALUES (4,'')
My result should be as below:
id CounrtyName
1 {"India":"BAN":"USA"}
2 {"Japan":"China"}
3 {"Switzerland"}
4
Can anyone please suggest me the query for the above data.
Thanks
FOR JSON
isn't available in SQL Server 2014 (though as Martin mentions, this isn't valid JSON data), but at the end of the day, this is just a Colon (:
) delimited string wrapped in braces ({}
); and bothSTUFF
andFOR XML PATH
are available in SQL Server 2014.{"India":"BAN":"USA"}
{"India":"BAN":"USA"}
is not valid. In JSON that would more naturally be represented as{"Countries": ["India","BAN","USA"]}
or similar.