使用json\u查询连接数组值

pdsfdshx  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(252)

我在SQLServer数据库中有一个表,它在其中一列中存储json。结构如下:
餐桌上的人

| Name   |      ExtraInfo                             |
|--------|:------------------------------------------:|
| Bob    |  {"Age":"23","Colors":["Red","Blue"]}      |
| James  |  {"Age":"26","Colors":["Green","Yellow"]}  |

如果我运行此查询:

select
Json_value(ExtraInfo,'$.Age') as Age,
json_query(ExtraInfo, '$.Colors') as Colors
from Persons

我会得到这样的结果:

| Age |Colors              |
|-----|:-------------------|
| 23  |  ["Red","Blue"]    |
| 26  |  ["Green","Yellow"]|

但是我需要改变 Colors json数组的属性 nvarchar 列,数组的所有值由如下空格字符连接:

| Age | Colors       |
|-----|:-------------|
| 23  | Red Blue     |
| 26  | Green Yellow |

有没有什么方法可以让我打多个电话给你 json_query 或者其他类似的方法在一个sql查询中实现这一点?

xwmevbvl

xwmevbvl1#

一种选择是使用 CROSS APPLY 以及 string_agg() 例子

Declare @YourTable Table ([Name] varchar(50),[ExtraInfo] varchar(50))  Insert Into @YourTable Values 
 ('Bob','{"Age":"23","Colors":["Red","Blue"]}')
,('James','{"Age":"26","Colors":["Green","Yellow"]}')

Select Json_value(ExtraInfo,'$.Age') as Age
      ,B.*
 From @YourTable A
 Cross Apply (
                Select Colors = STRING_AGG( value ,' ')
                 From  OpenJSON(json_query(ExtraInfo, '$.Colors'),'$')
             ) B

退货

Age Colors
23  Red Blue
26  Green Yellow

相关问题