SQL OPENJSON function
FROM OPENJSON(@items) WITH (sku nvarchar(40), qty int) reads a JSON array as a table. Use CROSS APPLY to shred a JSON column row by row.
- Categoria
- Strings
- Returns
rowset- In this category
- 154 of 172
Sintaxe
OPENJSON(json_doc [, path]) [WITH (column_defs)]
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | Supported under this name. |
| PostgreSQL | Not built in | jsonb_to_recordset or jsonb_populate_recordset |
| MySQL | Not built in | JSON_TABLE |
| SQLite | Not built in | json_each |
| Oracle | Not built in | JSON_TABLE |
Exemplos
SQL Server
DECLARE @items nvarchar(max) = N'[{"sku":"A1","qty":2},{"sku":"B2","qty":5}]';
SELECT *
FROM OPENJSON(@items)
WITH (sku nvarchar(40) '$.sku',
qty int '$.qty');
SQL Server
DECLARE @config nvarchar(max) = N'{"region":"eu","tags":["a"],"n":3}';
SELECT [key], [value], [type]
FROM OPENJSON(@config); -- types 1, 4, 2
SQL Server
SELECT o.id, i.sku, i.qty FROM orders o CROSS APPLY OPENJSON(o.items) WITH (sku nvarchar(40) '$.sku', qty int '$.qty') i;
Bom saber
- Without WITH you get three columns: key, value (nvarchar) and type (0 null, 1 string, 2 number, 3 boolean, 4 array, 5 object). With WITH, the declared columns and paths take over.
- OPENJSON needs database compatibility level 130 or higher; on a database still at 120 it fails with a syntax error even on a new server.
- It is a table-valued function: put it in FROM, or CROSS APPLY it per row to shred a JSON column of the outer table.
- The second argument is the path root: OPENJSON(@doc, '$.items') shreds the nested array directly instead of the whole document.
Questions about OPENJSON
OPENJSON or JSON_TABLE?
The same job in two dialects: OPENJSON is T-SQL, JSON_TABLE is the SQL standard (Oracle, MySQL, PostgreSQL 17). Porting means rewriting the COLUMNS clause either way.
Why are all my OPENJSON columns nvarchar?
You omitted the WITH clause, so OPENJSON returned its generic schema. Add WITH (col type '$.path', ...) to get typed columns.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.