使用 JSON_VALUE 解析 SQL 服务器 table 中的列
Using JSON_VALUE for parse column in SQL Server table
我之前从未在 SQL 服务器中使用过 JSON,所以需要一些帮助。
我写了一段简单的代码:
DECLARE @json NVARCHAR(4000)
SET @json =
N'{
"id":"40476",
"tags":[
{
"id":"5f5883",
},
{
"id":"5fc8",
}
],
"type":"student",
"external_id":"40614476"
}'
SELECT
JSON_value(@json, '$.tags[0].id') as tags
在上面的示例中,我编写了如何从“标签”中获取第一个“id”的代码。
但是如果在“标签”中不是 2 个“id”,而是一个未知数字,这个“id”和结果应该在这样的列中,看起来像脚本:
1 5f5883
2 5fc8
您可以使用带有显式模式的 OPENJSON()
来解析 $.tags
JSON 数组:
DECLARE @json NVARCHAR(4000)
SET @json =
N'{
"id":"40476",
"tags":[
{
"id":"5f5883"
},
{
"id":"5fc8"
}
],
"type":"student",
"external_id":"40614476"
}'
SELECT id
FROM OPENJSON(@json, '$.tags') WITH (id varchar(10) '$.id')
结果:
id
------
5f5883
5fc8
如果要获取 $.tags
JSON 数组中每个 id
的索引,则需要将 OPENJSON()
与默认架构和 JSON_VALUE()
:
SELECT CONVERT(int, [key]) AS rn, JSON_VALUE([value], '$.id') AS id
FROM OPENJSON(@json, '$.tags')
结果:
rn id
----------
0 5f5883
1 5fc8
我之前从未在 SQL 服务器中使用过 JSON,所以需要一些帮助。
我写了一段简单的代码:
DECLARE @json NVARCHAR(4000)
SET @json =
N'{
"id":"40476",
"tags":[
{
"id":"5f5883",
},
{
"id":"5fc8",
}
],
"type":"student",
"external_id":"40614476"
}'
SELECT
JSON_value(@json, '$.tags[0].id') as tags
在上面的示例中,我编写了如何从“标签”中获取第一个“id”的代码。
但是如果在“标签”中不是 2 个“id”,而是一个未知数字,这个“id”和结果应该在这样的列中,看起来像脚本:
1 5f5883
2 5fc8
您可以使用带有显式模式的 OPENJSON()
来解析 $.tags
JSON 数组:
DECLARE @json NVARCHAR(4000)
SET @json =
N'{
"id":"40476",
"tags":[
{
"id":"5f5883"
},
{
"id":"5fc8"
}
],
"type":"student",
"external_id":"40614476"
}'
SELECT id
FROM OPENJSON(@json, '$.tags') WITH (id varchar(10) '$.id')
结果:
id
------
5f5883
5fc8
如果要获取 $.tags
JSON 数组中每个 id
的索引,则需要将 OPENJSON()
与默认架构和 JSON_VALUE()
:
SELECT CONVERT(int, [key]) AS rn, JSON_VALUE([value], '$.id') AS id
FROM OPENJSON(@json, '$.tags')
结果:
rn id
----------
0 5f5883
1 5fc8