Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect syntax near 'JSON' - SQL Server 2014

Tags:

sql

sql-server

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
like image 813
Tanveer Hussain Avatar asked Jul 29 '26 04:07

Tanveer Hussain


2 Answers

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

like image 194
Vahid Farahmandian Avatar answered Jul 31 '26 18:07

Vahid Farahmandian


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,''
          ) + ']';
like image 33
Dan Avatar answered Jul 31 '26 20:07

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!