Multiple SQL columns into 1 json column

Viewed 2496

I am new to querying and using JSON fields. I've done some research, but most of the info I find is regarding querying from JSON to rows and columns. My question is in opposite direction:

Let's say I have a table with 3 columns: (Age, Optin, City). Now i want to add one column in JSON format. I tried:

SELECT Age, Optin, City
INTO #JSON_Table
FROM MyTable
FOR JSON AUTO

Error message: Msg 13602, Level 16, State 1, Line 30 The FOR JSON clause is not allowed in a SELECT INTO statement.

Pretty basic stuff, I know, but I could use some assistence.

2 Answers
select * into #JSON_Table
from (SELECT Age, Optin, City
FROM MyTable
FOR JSON PATH
) a(X)

Where X is the column name

Try this query and also check with the sql server versions. some versions of sql like SQL SERVER 2012 doesn't supports this query and 2016 will does.

select * into #JSON_Table from (SELECT Age, Optin, City FROM MyTable FOR JSON PATH ) a

Related