--创建测试表
create table #temp (seq int identity,names varchar(200))
insert into #temp(names)
values('张三,李四'),
('中国,美国,巴西'),
('深圳,上海,北京,广州,哈尔滨'),
('足球,篮球,乒乓球,台球')

 

目的是要将用逗号分隔的names列拆分为多行,最终要产生的结果为:

1 张三

1 李四
2 中国
2 美国
2 巴西
3 深圳
3 上海
3 北京
3 广州
3 哈尔滨
4 足球
4 篮球
4 乒乓球
4 台球

 

 1 ;with cte as(
 2 select 0 as n
 3 union all
 4 select N+1 from cte where n<100
 5 )
 6 ,idx as (
 7 select a.seq,b.n,ROW_NUMBER() over (partition by a.seq order by b.n) as id,','+a.names+',' as names
 8 from #temp a
 9     inner join cte b on b.n<=len(','+a.names+',' )
10 where SUBSTRING(','+a.names+',',b.n,1)=','
11 )
12 select a.seq,substring(a.names,a.n+1,b.n-a.n-1) as name
13 from idx a
14     inner join idx b on a.seq=b.seq and a.id=b.id-1

 

相关文章:

  • 2022-12-23
  • 2021-07-19
  • 2021-09-21
  • 2021-11-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-19
猜你喜欢
  • 2022-12-23
  • 2022-02-07
  • 2022-12-23
  • 2021-09-25
  • 2021-04-03
  • 2021-10-31
  • 2021-08-07
相关资源
相似解决方案