使用 Json_Query 连接数组值
Concatenate Array Values Using Json_Query
我在 SQL 服务器数据库中有一个 table,其中一列存储 JSON。结构如下:
Table 人
| 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"]|
但是我需要将 JSON 数组的 Colors
属性 转换为 nvarchar
列,数组的所有值由 space 像这样的字符:
| Age | Colors |
|-----|:-------------|
| 23 | Red Blue |
| 26 | Green Yellow |
有什么方法可以组合对 json_query
的多个调用或其他类似方法来在单个 SQL 查询中完成此操作?
一种选择是使用 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
Returns
Age Colors
23 Red Blue
26 Green Yellow
我在 SQL 服务器数据库中有一个 table,其中一列存储 JSON。结构如下:
Table 人
| 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"]|
但是我需要将 JSON 数组的 Colors
属性 转换为 nvarchar
列,数组的所有值由 space 像这样的字符:
| Age | Colors |
|-----|:-------------|
| 23 | Red Blue |
| 26 | Green Yellow |
有什么方法可以组合对 json_query
的多个调用或其他类似方法来在单个 SQL 查询中完成此操作?
一种选择是使用 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
Returns
Age Colors
23 Red Blue
26 Green Yellow