我正在尝试将一个 json 数组读入一个表,该数组中的一个节点(语言)本身就是一个数组,我正在为这个特定的列(语言)获取 null
.
下面是示例 json:
DECLARE @json NVARCHAR(MAX) = '[
{
"Id":1,
"Name":"Test1",
"Languages":["L1", "L2"]
},
{
"Id":2,
"Name":"Test2",
"Languages":["L3", "L4"]
},
{
"Id":3,
"Name":"Test2",
"Languages":["L5", "L6"]
}]'
下面是我正在使用的查询:
SELECT Id
, Name
, Languages
FROM OPENJSON(@json)
WITH (Id INT '$.Id'
, Name VARCHAR(20) '$.Name'
, Languages VARCHAR(200) '$.Languages')
下面是当前结果:
但是我需要如下结果
我做错了什么?请帮忙。
最佳答案
对于 WITH
子句中的语言项,您可以使用 NVARCHAR(max) as json
。
来自 Microsoft 文档(可以找到所有详细信息 here ):
If you don't specify AS JSON for a column, the function returns a scalar value (for example, int, string, true, false) from the specified JSON property on the specified path. If the path represents an object or an array, and the property can't be found at the specified path, the function returns null in lax mode or returns an error in strict mode. This behavior is similar to the behavior of the JSON_VALUE function.
所以你的查询应该是这样的:
SELECT Id
, Name
, Languages
FROM OPENJSON(@json)
WITH (Id INT '$.Id'
, Name VARCHAR(20) '$.Name'
, Languages NVARCHAR(max) as json)
结果:
关于sql - 读取 JSON 数组作为 SQL 表列之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52376966/