T-SQL Tutorial


JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. SQL Server 2016 and later versions have built-in support for storing, querying, and manipulating JSON data.

In SQL Server, you can use the FOR JSON clause to convert the results of a query into JSON format. The FOR JSON clause can be used in SELECT, INSERT, UPDATE, and DELETE statements. You can also use the OPENJSON function to parse JSON data and convert it into a tabular format that can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Additionally, SQL Server provides functions such as JSON_VALUE and JSON_QUERY to extract a scalar value or an object from a JSON string, and ISJSON to check if a string is a valid JSON. It is worth mentioning that the JSON support in SQL Server is limited to the manipulation of text data, and it doesn't provide indexing or querying capabilities for JSON data, for that you need a NoSQL database like MongoDB or CosmosDB.

JSON functions in SQL Server

SQL Server provides several functions to work with JSON data. These functions include:

1. JSON_VALUE: This function extracts a scalar value from a JSON string. For example, you can use the JSON_VALUE function to extract the value of a specific key from a JSON string.

2. JSON_QUERY: This function extracts an object or an array from a JSON string. This function is similar to JSON_VALUE, but it returns a JSON object or array instead of a scalar value.

3. ISJSON: This function checks if a string is a valid JSON. It returns 1 if the input string is a valid JSON, otherwise it returns 0.

4. JSON_MODIFY: This function is used to update the value of a property in a JSON string.

5. JSON_OBJECT: This function constructs a text JSON object from zero or more expressions and returns a valid JSON object string.

6. JSON_PATH_EXISTS: This function checks if a specified SQL/JSON path exists in the input JSON string.

7. OPENJSON: This function parses JSON text and returns the JSON values as a rowset that can be queried using the SELECT statement.

8. JSON_ARRAY: This function generates a JSON array from a set of expressions.

These functions allow you to work with JSON data in SQL Server and extract or update values, or check if the JSON is valid. These functions can be used in SELECT, INSERT, UPDATE, and DELETE statements.