sql - 读取 JSON 数组作为 SQL 表列之一

标签 sql arrays json sql-server tsql

我正在尝试将一个 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')

下面是当前结果:

enter image description here

但是我需要如下结果

enter image description here

我做错了什么?请帮忙。

最佳答案

对于 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)

结果:

enter image description here

关于sql - 读取 JSON 数组作为 SQL 表列之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52376966/

相关文章:

php - 使用LIMIT的Mysql表,随机中断

mysql - 按其他日期分割日期

mysql - 没有 double 的sql查询连接

c++ - GCC C++编译器中的零大小数组

java - 为什么数组中有多余的值?

json - 如何获取 JSON 中某个键的值?

sql - 在 SQL 中使用多个表进行全文搜索

mysql - 不在查询中的列的更新语句中的未知列

javascript - 循环遍历数组内部时如何获取数组的名称?

php - 将 jQuery 数组字符串转换为 PHP 数组