回复:【挑战TSQL】将字符串里重复出现的字符去掉后按照出现的顺序重新形成一个新的字符
DECLARE @t TABLE (id int identity,Data VARCHAR(40) )
INSERT @t (Data) select 'XEDDDEFFE'
INSERT @t (Data) SELECT 'FWRRFXPPLW';
with cte_r as
(
select a.id,a.Data,Char=substring(a.Data,b.number+1,1),b.number
from @t a inner join
master.dbo.spt_values b on b.type='P' and b.number<len(a.Data)
)
,
cte_r1 as
(
select id,Data,Char=cast(Char as varchar(40)),number from cte_r where number=0
union all
select a.id,a.Data,Char=cast(case when charindex(b.Char,a.Char)>0 then a.Char else a.Char+b.Char end as varchar(40)),b.number
from cte_r1 a inner join
cte_r b on a.id=b.id and a.number+1=b.number
)
select id,Data,Char from cte_r1 a
where not exists(select * from cte_r1 where id=a.id and number>a.number)
order by 1
--or
--select id,Data,Char from cte_r1 a
--where number=(select max(number) from cte_r1 where id=a.id)
--order by 1
组合字符串也可用xml实现拼接