How to Insert JSON into a Table in SQL Server

If you have a JSON document that you need to insert into a table in a SQL Server database, the OPENJSON() function could be just what you need.

OPENJSON() is a table-valued function that returns JSON in tabular format. That is, it converts your JSON into a tabular result set consisting of rows and columns. Therefore, it enables you to insert it into a table.

Continue reading

How to Return Duplicate Keys from a JSON Document in SQL Server

If you’re trying to extract values from a JSON document, but one or more of the values on the same level have duplicate keys, you might run into problems if you try to extract those values using JSON_QUERY() or JSON_VALUE().

Both of those functions will only return the first value that matches the path. 

Fortunately, there’s another option.

The OPENJSON() function will return all values from any duplicate keys on the same level.

Continue reading

OPENJSON “Incorrect syntax near the keyword ‘with’.” in SQL Server (SOLVED)

If you’re trying to run some OPENJSON() code in SQL Server, but you’re getting error Msg 319, Level 15 “Incorrect syntax near the keyword ‘with'”, one possibility is that you really do have a syntax error.

But if you’ve check and double checked, and you’re convinced there’s no syntax error, it could actually be that the error is a side effect of having the wrong database compatibility level.

Normally you’d get error Msg 208, Level 16 “Invalid object name ‘OPENJSON’.” when using a database compatibility level of lower than 130, but in some cases, SQL Server finds a problem with the WITH clause first.

Continue reading

How to Fix “Invalid object name ‘OPENJSON’.” in SQL Server

If you encounter error Msg 208, Level 16 “Invalid object name ‘OPENJSON’.”, you are probably trying to use the OPENJSON() function on a database with a compatibility level of less than 130.

OPENJSON() is only available under compatibility level 130 or higher.

To fix this, either increase the compatibility level of your database to 130 or higher, or change to a database that already has the appropriate compatibility level.

Continue reading