【问题标题】:Concatenate Array Values Using Json_Query使用 Json_Query 连接数组值
【发布时间】:2020-05-28 01:13:59
【问题描述】:

我在 SQL Server 数据库中有一个表,它在其中一个列中存储 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"]|

但是,我需要将 JSON 数组的 Colors 属性转换为 nvarchar 列,其中数组的所有值由空格字符连接,如下所示:

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

有什么方法可以组合多个调用json_query 或其他类似方法在单个 SQL 查询中完成此操作?

【问题讨论】:

    标签: sql arrays sql-server json-query open-json


    【解决方案1】:

    一种选择是使用CROSS APPLYstring_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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 2020-11-25
      • 2022-11-19
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多