0

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

6
  • What have you tried so far? 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 both STUFF and FOR XML PATH are available in SQL Server 2014. Commented Mar 3, 2020 at 11:34
  • Does this answer your question? Comma separated results in SQL Commented Mar 3, 2020 at 11:34
  • 1
    This is not valid JSON: {"India":"BAN":"USA"} Commented Mar 3, 2020 at 11:35
  • 2
    Note that the format you've suggested is not JSON. Specifically, JSON is a key/value format; {"India":"BAN":"USA"} is not valid. In JSON that would more naturally be represented as {"Countries": ["India","BAN","USA"]} or similar. Commented Mar 3, 2020 at 11:36
  • Sorry yes I need in the format of {"India","BAN","USA"} without Key Commented Mar 3, 2020 at 11:51

1 Answer 1

2

Your expected output looks nothing like JSON. Having said that, you could use the following to generated the expected result:

SELECT id, '{' + STUFF((
    SELECT ',"' + NULLIF(CountryName, '') + '"'
    FROM @country AS y
    WHERE y.id = x.id
    FOR XML PATH('')
), 1, 1, '') + '}'
FROM @country AS x
GROUP BY id
Sign up to request clarification or add additional context in comments.

7 Comments

I am getting "'STRING_ESCAPE' is not a recognized built-in function name" error
Which version of SQL Server are you using?
string_escape was introduced in 2016 version, string_agg in 2017. The OP is working with 2014 version, meaning no built-in JSON support hence the question...
I am using 2014 version
@Bhushan see revised answer.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.