3

I wanted to know if there is any function or something to convert the SQL select query result to JSON string format?

For example, SQL select query result is,

current   target
-----------------
  500      1000
  1500     2000

JSON result:

[{"current":500,"target":1000},{"current":1500,"target":2000}]

Any ideas will be helpful.

Thanks.

M.Ali
  • 65,124
  • 12
  • 92
  • 119
Arpita
  • 415
  • 3
  • 13
  • 28

2 Answers2

5

SQL Fiddle

MS SQL Server 2008 Schema Setup:

Query 1:

DECLARE @TABLE TABLE ([current] INT, [target] INT)
INSERT INTO @TABLE VALUES 
(500   ,   1000),
(1500  ,   2000)


SELECT '[' +  STUFF((SELECT ',{"current":' + CAST([current] AS VARCHAR(30)) 
   + ',"target":' + CAST([target] AS VARCHAR(30)) + '}'
FROM @TABLE
FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,1,'') + ']'

Results:

[{"current":500,"target":1000},{"current":1500,"target":2000}] 
M.Ali
  • 65,124
  • 12
  • 92
  • 119
  • I would update code to include the inner quotes: ``+ CAST([target] AS VARCHAR(30)) +`` to ``+ '"' + CAST([target] AS VARCHAR(30)) + '"'`` – Ravi Ram Jun 15 '17 at 04:16
4

You don't specify version.

In SQL Server 2016 you will be able to do something like

SELECT [current], 
       target
FROM YourTable
ORDER BY [current]
FOR JSON AUTO;

More details here or in the official pre release documentation

Martin Smith
  • 419,657
  • 83
  • 708
  • 800