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

SQL 如何去除重复的字符串
例如 我查出一串字符 结果如下 
SQL code


'APR-11,APR12,APR06,APR-11,APR12,APR06'



如何去除重复的 只保留一个

------解决方案--------------------
SQL code
declare @ret varchar(8000)
select @ret = 'APR-11,APR12,APR06,APR-11,APR12,APR06'

select distinct name=substring(@ret,number,charindex(',',@ret+',',number)-number)
from master..spt_values
where number<=len(@ret) and type='P' 
and substring(','+@ret,number,1)=','
--------------------------
APR06
APR-11
APR12

------解决方案--------------------
SQL code



create function GetDistinct(@str varchar(1000))
returns varchar(1000)
as
begin
    declare @temp varchar(1000)
    while(charindex(','+substring(@str,1,charindex(',',@str)-1)+',',','+isnull(@temp,'')+',')=0)
    begin
        set @temp=isnull(@temp+',','')+substring(@str,1,charindex(',',@str)-1)
        set @str=substring(@str,charindex(',',@str)+1,len(@str))
    end
    return @temp
end
go

select dbo.getdistinct('APR-11,APR12,APR06,APR-11,APR12,APR06')
--结果:
--------------------------
APR-11,APR12,APR06