方法1:使用with...as...和substring实现字段按行拆分操作
--1、建立临时范例表
drop table #temp
create table #temp (seq int identity,names varchar(200))
insert into #temp(names)
values('A,B'),
('男,女'),
('XL码,L码,M码,S码'),
('一线城市,二线城市,三线城市,四线城市')
select * from #temp --生成需要拆分字段的数据表
--2、对names字段根据,进行拆分
;with ids as (
select 0 an id
union all
select id+1 from ids where id<50
) --select * from ids --递归生成按行显示的0-50的表
,split as (
select a.seq,b.n,ROW_NUMBER() over (partition by a.seq order by b.n) as id,','+a.names+',' as names
from #temp a
inner join ids b on b.n<=len(','+a.names+',' )
where SUBSTRING(','+a.names+',',b.n,1)=','
) --select * from split
select a.seq,substring(a.names,a.n+1,b.n-a.n-1) as name
from split a
inner join split b on a.seq=b.seq and a.id=b.id-1
运行结果如下:

方法2:使用cross apply实现实现字段按行拆分操作
drop table #temp
create table #temp (id int identity,names varchar(200))
insert into #temp(names)
values('A,B'),
('男,女'),
('XL码,L码,M码,S码,'),
('一线城市,二线城市,三线城市,四线城市')
select distinct id,ListItem
from #temp
cross apply (select description1=(select [*]=names for xml path(''))) C0
cross apply (select description2='<x>'+replace(description1,',','</x><x>')+'</x>') C1
cross apply (select XMLEncoded=cast(description2 as xml)) C2
cross apply XMLEncoded.nodes('x') C3(XmlNode)
cross apply (select ListItem=XmlNode.value('.','varchar(50)')) C4
运行结果:

备注:以上方法都是工作中比较常用,经过整理得到,行转列方法可以参考历史文章
本文介绍两种实用的SQL字段拆分方法:一是利用with...as...和substring进行字段按行拆分;二是采用cross apply实现字段拆分。通过具体实例展示如何将含有逗号分隔值的字段拆分为多行,适用于数据清洗和预处理场景。
7310

被折叠的 条评论
为什么被折叠?



