liveBook · Manning

Openjson

As explained in 100 SQL Server Mistakes and How to Avoid Them

OPENJSON is a SQL Server table-valued function that parses JSON text and exposes its elements as relational rows and columns.

A common mistake is treating JSON as automatically relational. When an array path omits its index, JSON_VALUE returns NULL; OPENJSON instead shreds the selected document portion into rows and typed columns without document preparation. section 3.5

Employee address extraction

OPENJSON(@EmployeeAddress, '$.EmployeeAddress[0]') selects one array element. A WITH clause maps EmployeeID, address paths, and SQL data types into relational columns. section 3.5

Listing 3.24 Shredding the JSON data into relational values
DECLARE @EmployeeAddress NVARCHAR(MAX) ;

SET @EmployeeAddress = (
   SELECT
         1 AS 'EmployeeID'
       , '5331 Rexford Court' AS 'Address.Line1'
       , 'Montgomery'         AS 'Address.City'
       , 'AL'                 AS 'Address.State'
       , '36116'              AS 'Address.ZipCode'
   FOR JSON PATH, ROOT ('EmployeeAddress')
) ;

SELECT *
FROM OPENJSON(@EmployeeAddress, '$.EmployeeAddress[0]')
WITH (
   EmployeeID SMALLINT,
   Line1 NVARCHAR(64) '$.Address.Line1',
   City NVARCHAR(64) '$.Address.City',
   [State] NCHAR(2) '$.Address.State',
   ZipCode NVARCHAR(10) '$.Address.ZipCode'
) ;

Inspect the complete T-SQL pattern for shredding an employee address JSON document into relational values. section 3.5

How 100 SQL Server Mistakes and How to Avoid Them covers it

How deep it goes
Explains document paths, array indexing, WITH mappings, and SQL types, without descending into function internals.
Examples
Uses an employee address document containing EmployeeID, street, city, state, and ZIP code fields.
What it assumes
Assumes basic SQL statements and JSON path notation, while demonstrating array indexing and nested-property mapping.
What you can do after
Apply OPENJSON with a path and WITH clause to project nested JSON values into typed relational columns.
How it connects
Connects JSON parsing with JSON_VALUE, OPENXML, relational data, denormalization, NoSQL, and APIs.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 SQL Server Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.