How can I combine several columns (of varying types, e.g. int, datetime, nvarchar) as a single JSON-formatted expression in a select query? For example, I have columns col1, col2 and want the query to return a single column where each row like this:
{col1: val1, col2: val2}
Can I use FOR JSON? I'm using SQL Server 2017, but the database I'm querying is 2008 (100) compatibility mode.
Best Answer
All the JSON syntax works regardless of compatibility level.
Results:
If you need it without the square brackets, you'll need to abstract it away so you can assign a column name to the JSON output:
Results:
And without quotes:
Results:
And yes it works with all types:
Results:
This assumes you don't have the closing square bracket
]
in your data. If you do, you'll either need to double it on extraction, beforeFOR JSON
looks at it, or else use a more tedious method thanPARSENAME()
to removing the outer square brackets.