日期:2014-05-18  浏览次数:20450 次

请教哈谁有好方法把一个字符串中的冗余项(即有相同项的只显示一项)剔出掉啊
如题:例如9,12,13,12,13,13,9,10,13,11,12,13,9,10,11,9,13,11,11,13要得到最后结果为9,10,11,12,13

------解决方案--------------------
declare @FullString varchar(1000),
@DistinctString varchar(1000)

set @FullString = '9,12,13,12,13,13,9,10,13,11,12,13,9,10,11,9,13,11,11,13 '
set @FullString = @FullString + ', '
set @DistinctString = ' '

while @FullString <> ' '
begin
select @DistinctString = @DistinctString + ', ' + left(@FullString,charindex( ', ',@FullString)-1),
@FullString=replace(@FullString,left(@FullString,charindex( ', ',@FullString)), ' ')
end

select @DistinctString=stuff(@DistinctString,1,1, ' ')
select @DistinctString
------解决方案--------------------
create function fnDistinct(@FullString varchar(1000))
returns varchar(1000) as
begin
declare @DistinctString varchar(1000)
set @DistinctString = ' '
set @FullString = @FullString + ', '
while @FullString <> ' '
begin
select @DistinctString = @DistinctString + ', ' + left(@FullString,charindex( ', ',@FullString)-1),
@FullString=replace(@FullString,left(@FullString,charindex( ', ',@FullString)), ' ')
end
select @DistinctString=stuff(@DistinctString,1,1, ' ')
return @DistinctString
end

go
select dbo.fnDistinct( '9,12,13,12,13,13,9,10,13,11,12,13,9,10,11,9,13,11,11,13 ')

go
drop function dbo.fnDistinct
------解决方案--------------------
create proc p_str(@str varchar(2000))
as
declare @e varchar(8000),@c varchar(2000)
select @e= ' '
set @e=replace( ', '+@str, ', ', ' union all select ')
set @e=stuff(@e,1,len( ' union all '), ' ')

if object_id( 't1 ') <> ' ' drop table t1
if object_id( 't2 ') <> ' ' drop table t2
create table t1(col int)

insert into t1
exec (@e)
select distinct col into t2 from t1
set @c= ' '
select @c=@c+ ', '+convert(varchar(20),col) from t2
set @c=stuff(@c,1,1, ' ')
select @c



--测试

p_str '9,12,13,12,13,13,9,10,13,11,12,13,9,10,11,9,13,11,11,13 '

/*
结果
----------------
9,10,11,12,13

*/




------解决方案--------------------
declare @str varchar(100),@result varchar(100)
set @str= '9,12,13,12,13,13,9,10,13,11,12,13,9,10,11,9,13,11,11,13 '
set @str=@str+ ', '

while @str <> ' '
select
@result=coalesce(@result+ ', ', ' ')+left(@str,charindex( ', ',@str)-1),
@str=replace(@str,left(@str,charindex( ', ',@str)), ' ')
print @result --9,12,13,10,11

------解决方案--------------------
declare @str varchar(100),@result varchar(100),@tmp varchar(10)
set @str= '9,12,13,12,13,13,9,10,13,11,12,13,9,10,11,9,13,11,11,13 '
set @str= ', '+@str+ ', '

while @str <> ', '
begin
set @tmp=left(@str,charindex( ', ',@str,2))
set @result=coalesce(@result+ ', ', ' ')+replace(@tmp, ', ', ' ')
while charindex(@tmp,@str)> 0 set @str=replace(@str,@tmp, ', ')