I am looking to create well formatted JSON from a SQL Server stored procedure.
My problem is as follows:
Creating JSON like:
DECLARE @x varchar(20)
DECLARE @y varchar(20)
CREATE TABLE #temp
(
JSON varchar(max)
)
INSERT INTO #temp
VALUES (
'{' +
case when x IS NOT NULL BEGIN
'"key1":"' + x + '"' +
END
case when y IS NOT NULL BEGIN
'"key1":"' + y + '"' +
END
'}')
What is the best way to have "s" be well formatted json?? I would like to minimize the logic as much as possible (i.e. not have a branch for each of x*y combinations).
If a comma is put at the end of the x if conditions, it fails if y is null. If a comma is put before inserting y into the json, it fails if x is null.
Is there a better way to achieve this in SQL Server?