sql MS SQL OPENJSON
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql MS SQL OPENJSON相关的知识,希望对你有一定的参考价值。
-- Json Collection to Row Set (TYPE 1)
DECLARE @json NVARCHAR(MAX);
SET @json
= N'[
{
"id" : 6,
"info": { "name": "John", "surname": "Doe" },
"age": 25
},
{
"id" : 25,
"info": { "name": "Jane", "surname": "Doe" },
"dob": "2005-11-04T12:00:00"
}
]';
SELECT *
FROM
OPENJSON(@json)
WITH
(
id INT 'strict $.id',
fName NVARCHAR(50) '$.info.name',
lName NVARCHAR(50) '$.info.surname',
age INT,
dob DATETIME2 '$.dob'
);
-- OUTPUT
-- id | fName | lName | age | dob
-- 6 | John | Doe | 25 | NULL
-- 5 | Jane | Smith | NULL | 2005-11-04 12:00:00.0000000
-- Json Collection to Row Set (TYPE 2)
DECLARE @json NVARCHAR(MAX);
SET @json
= N'[
{
"id" : 23,
"info": { "name": "John", "surname": "Doe" },
"age": 25,
"Phones": ["123","345","678"]
},
{
"id" : 33,
"info": { "name": "Jane", "surname": "Doe" },
"dob": "2005-11-04T12:00:00",
"Phones": ["321","543"]
}
]';
SELECT id, [name], [surname], age, dob, number
FROM
(
SELECT *
FROM
OPENJSON(@json)
WITH
(
id INT 'strict $.id',
[name] NVARCHAR(50) '$.info.name',
[surname] NVARCHAR(50) '$.info.surname',
age INT,
dob DATETIME2 '$.dob',
Phones NVARCHAR(MAX) AS JSON
)
) AS people
OUTER APPLY
OPENJSON(Phones)
WITH
(
number NVARCHAR(50) '$'
);
-- OUTPUT
-- id | name | surname | age | dob | number
-- 2 John Smith 25 NULL 123
-- 2 John Smith 25 NULL 345
-- 2 John Smith 25 NULL 678
-- 3 Jane Smith NULL 2005-11-04 12:00:00.0000000 321
-- 3 Jane Smith NULL 2005-11-04 12:00:00.0000000 543
以上是关于sql MS SQL OPENJSON的主要内容,如果未能解决你的问题,请参考以下文章
MS SQL读取JSON数据
OPENJSON 在 SQL Server 中不起作用?
如何反转 SQL Server 中的 OPENJSON() 函数?
sql OPENJSON功能
OPENJSON 不会将所有文档都选择到 SQL 表中
SQL OPENJSON 到单列