JSON到SQL Server:将值的子数组转换为列

时间:2016-09-07 14:54:42

标签: sql-server json azure-sql-database sql-server-2016

我有像JSON一样的

{  
    "url": {
        "web_categories": [{ "id": 226 } , { "id": 401 }]
  },  
   "account":"Basic"  
}

我想在SQL中输出一个列,其中包含匹配的URL的所有web_categories的ID。

| webcat |
|--------|
| 226    |
| 401    |

使用SQL Server 2016 / Azure SQL DB对JSON的支持,如何实现这一目标?

可重复的例子

DECLARE @jsonInfo VARCHAR(MAX)  
SET @jsonInfo =N'{  
    "url": {
        "web_categories": [{ "id": 226 }]
  },  
   "account":"Basic"  
}'  

以前的迭代

select * from openjson(@jsonInfo)  with (webcat varchar(12) '$.url.web_categories.id[0]')
select * from openjson(@jsonInfo)  with (webcat varchar(12) '$.url.web_categories.id')
select * from openjson(@jsonInfo)  with (webcat varchar(12) '$.url.web_categories')
select * from openjson(@jsonInfo,'$.url.web_categories.id[0]')
select * from openjson(@jsonInfo,'$.url.web_categories.id')
select * from openjson(@jsonInfo,'$.url.web_categories')
select JSON_QUERY(@jsonInfo, '$.url.web_categories.id[0]') webcat
select JSON_QUERY(@jsonInfo, '$.url.web_categories.id')    webcat
select JSON_QUERY(@jsonInfo, '$.url.web_categories')       webcat
select JSON_VALUE(@jsonInfo, '$.url.web_categories.id[0]') webcat
select JSON_VALUE(@jsonInfo, '$.url.web_categories.id')    webcat
select JSON_VALUE(@jsonInfo, '$.url.web_categories')       webcat

1 个答案:

答案 0 :(得分:2)

使用默认架构,将返回包含value列的记录,该列包含阵列中每个项目的JSON。然后需要处理此JSON。

DECLARE @jsonInfo VARCHAR(MAX)  
SET @jsonInfo =N'{  
    "url": {
        "web_categories": [{ "id": 226 },{ "id": 411 }]
  },  
   "account":101  
}'  


 SELECT JSON_VALUE(value,'$.id') AS ids FROM OPENJSON(@jsoninfo,'$.url.web_categories')