SQL SERVER 特殊需求的一个替换实例 --【叶子】

需求贴:

http://topic.csdn.net/u/20120204/10/8b902fd2-8909-4ed9-b534-4a1a72454eff.html#r_77443331

需求简介:

比如:YYYYN,  结果处理为:人1,人2,人3,人4

分析:

貌似就是一个字符串的替换,如果是'Y'替换成'人'+Y的所在位置的编号。

解决方案:

declare @T table (id int,col varchar(5))
insert into @T
select 1,'YYYYN' union all
select 2,'YNNNY' union all
select 3,'NNNYN' union all
select 4,'YYNYN'

--1.第一种方法:case when
--最直观的处理方式 
select id,col=left(col,len(col)-1) from 
(
 select id,col=
 case when left(col,1)='Y' then '人1,' else '' end+
 case when substring(col,2,1)='Y' then '人2,' else '' end+
 case when substring(col,3,1)='Y' then '人3,' else '' end+
 case when substring(col,4,1)='Y' then '人4,' else '' end+
 case when substring(col,5,1)='Y' then '人5,' else '' end
 from @T
) a
/*
id          col
----------- --------------------
1           人1,人2,人3,人4
2           人1,人5
3           人4
4           人1,人2,人4
*/


--2.使用自定义函数 
--创建函数
create function fn_GetPersonCount
(
    @str varchar(5)
)
returns varchar(20)
as
begin
    declare @result varchar(20) set @result=''
    declare @i int set @i=0
    while(charindex('Y',@str)>0)
    begin
        set @result=@result+'人'+ltrim(charindex('Y',@str)+@i)+','
        set @str=right(@str,len(@str)-charindex('Y',@str))
        set @i=@i+1
    end
    set @result=left(@result,len(@result)-1)
    return @result
end

declare @T table (id int,col varchar(5))
insert into @T
select 1,'YYYYN' union all
select 2,'YNNNY' union all
select 3,'NNNYN' union all
select 4,'YYNYN'

select id,col=dbo.fn_GetPersonCount(col) from @T
/*
id          col
----------- --------------------
1           人1,人2,人3,人4
2           人1,人5
3           人4
4           人1,人2,人4
*/


--3.合并列值

declare @T table (id int,col varchar(5))
insert into @T
select 1,'YYYYN' union all
select 2,'YNNNY' union all
select 3,'NNNYN' union all
select 4,'YYNYN'

;with maco as
(
select a.*,'人'+ltrim(b.number+1) as c1 from @T a,master..spt_values b 
where b.type='p' and b.number <5 and substring(col,0+right(number+1,1),1)='Y'
)

select id, col=
stuff((select ','+c1 from maco t where id=maco.id for xml path('')), 1, 1, '')
from maco group by id

/*
id          col
----------- --------------------
1           人1,人2,人3,人4
2           人1,人5
3           人4
4           人1,人2,人4
*/


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值