一行变多行(整理总结)

--XML
DECLARE @one Table(    
    CompanyID INT,    
    CompanyCodes VARCHAR(100) 
) 
 
insert into @one select 1,'1|2' 
union all select 2,'1|2|3' 
union all select 3,'1|2|3|4'
union all select 4,'1|2|3|4|5'

;WITH cte AS ( 
    SELECT 
        CompanyID, 
        CAST('<i>' + REPLACE(CompanyCodes, '|', '</i><i>') + '</i>' AS XML) AS CompanyCodes
    FROM @one 
) 
SELECT 
    CompanyID, 
    x.i.value('.', 'VARCHAR(10)') AS CompanyCode 
FROM cte 
CROSS APPLY CompanyCodes.nodes('i') x(i) 

--案例二
declare @two table(autoid int,partid varchar(50),location varchar(100));
insert into @two(autoid,partid,location)
select 14,'HAMP-025-0002','C190 C234 C237' union all
select 15,'HAMP-025-0038','D27 D28 D29';


select a.autoId,a.partId,b.vx
from 
(select autoid,partid,cast('<root><v>'+REPLACE(location,' ','</v><v>')+'</v></root>' as xml) as x from @two) a
outer apply(
    select vx=N.v.value('.','varchar(100)') from a.x.nodes('/root/v') N(v)
) b

--案例 三
declare @three table
(id int,name char(1),yh varchar(20))

insert into @three
select 1, 'a', '0001,0002,0003' union all
select 2, 'b', '0002,0003' union all
select 3, 'c', '0001,0004'


select a.name,
substring(','+a.yh,b.number+1,charindex(',',a.yh+',',b.number)-b.number) 'yh'
from @three a
inner join master.dbo.spt_values b
on b.[type]='P' and 
substring(','+a.yh,b.number,1)=','


 


 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值