开发者社区> 问答> 正文

如何从逗号分隔的列表中创建多个记录

我正在使用SQL Server 2019来分隔逗号分隔的值列表。

我有一张看起来像下面的桌子

从我读过的StackOverflow来看,没有一个内置函数可以按我的意愿分割逗号。但是,我已经看到了String_Split我认为可能有用的交叉应用功能,但是我只能在单个列上使用它。

表结构如下:

CREATE TABLE neighbourhoods3.dbo.timeslots 
(
     year VARCHAR(50) NULL,
     time_of_day VARCHAR(50) NULL,
     day_of_week VARCHAR(50) NULL,
     month VARCHAR(50) NULL,
     season VARCHAR(50) NULL,
     public_holiday VARCHAR(50) NULL,
     public_holiday_minus_1 VARCHAR(50) NULL
) ON [PRIMARY]
GO

展开
收起
祖安文状元 2020-01-04 15:28:38 618 0
1 条回答
写回答
取消 提交回答
  • 遗憾的是,尽管SQL Server现在支持string_split(),但不能保证返回集的顺序。

    因此,我推荐一种替代方法,例如递归CTE。这是代码示例的示例:

    with cte as (
          select convert(varchar(max), NULL) as year,
                 convert(varchar(max), NULL) as time_of_day,
                 convert(varchar(max), NULL) as day_of_week,
                 convert(varchar(max), year) as year_rest,
                 convert(varchar(max), time_of_day) as time_of_day_rest,
                 convert(varchar(max), day_of_week) as day_of_week_rest
          from t
          union all
          select convert(varchar(max), left(year_rest, charindex(',', year_rest + ',') - 1)) as year,
                 convert(varchar(max), left(time_of_day_rest, charindex(',', time_of_day_rest + ',') - 1)) as time_of_day,
                 convert(varchar(max), left(day_of_week_rest, charindex(',', day_of_week_rest + ',') - 1)) as day_of_week,
                 stuff(year_rest, 1, charindex(',', year_rest + ','), '') as year_rest,
                 stuff(time_of_day_rest, 1, charindex(',', time_of_day_rest + ','), '') as time_of_day_rest,
                 stuff(day_of_week_rest, 1, charindex(',', day_of_week_rest + ','), '') as day_of_week_rest
          from cte
          where year_rest <> ''
         )
    select year, time_of_day, day_of_week
    from cte
    where year is not null;
    
    

    这是db <>

    2020-01-04 15:29:00
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载