2

I am trying to use it in my SQL Query exactly like it's shown in the link below on MSDN. The keyword JSON does not turn blue and gives error

Incorrect syntax near 'JSON'

What's wrong with it?

EDIT: I'm testing it for SQL Server 2014. The query is

SELECT * FROM food FOR JSON AUTO
3
  • 8
    JSON support starts from Sql 2016 Commented Mar 6, 2018 at 12:20
  • @abhishek what is the possible solution for this? Commented Mar 6, 2018 at 12:28
  • 2
    Upgrade. If you can't upgrade, do all JSON processing outside the database. They didn't add it as a feature to 2016 for nothing. Commented Mar 6, 2018 at 12:32

3 Answers 3

7

FOR JSON AUTO is available from SQL SERVER 2016. If you are using SQL SERVER 2014 or former, then you can use the following approach:

SELECT '['+ STUFF((
                SELECT ',{"Col1":"' + CAST(t1.name AS NVARCHAR(MAX)) + '",'+
                        +'"Col2":"'+CAST(t1.database_id AS NVARCHAR(MAX)) + '"}'
                    FROM Food t1 FOR XML PATH(''), TYPE
                  ).value('.', 'varchar(max)'),1,1,''
              ) + ']';

You can validate the output using various online tools such as JSON LINT to make sure that the result is valid json-formatted result.

Update:

Here is the screenshot of the code and result:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

@TanveerHussain recheck your query again. I have attached a screenshot of the query and result to my answer too
2

Thank you Vahid for the query very handy. Just a quick modification if the record have '\' in their value JSON will fail so modified the query to accommodate that

 SELECT '['+ STUFF((
      SELECT ',{"Col1":"' + REPLACE(CAST(t1.name  AS NVARCHAR(MAX)),'\','\\') + '",'+
           +'"Col2":"' + REPLACE(CAST(t1.value AS NVARCHAR(MAX)),'\','\\') + '"}'
                FROM Food t1 FOR XML PATH(''), TYPE
              ).value('.', 'varchar(max)'),1,1,''
          ) + ']';

Comments

1

JSON AUTO Only use in SQL Server 2016.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.