SQL SERVER通过特定符号对字符串循环切割,便于匹配或者行转列

方法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

运行结果:

备注:以上方法都是工作中比较常用,经过整理得到,行转列方法可以参考历史文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值