读书人

SQL 怎么去除重复的字符串

发布时间: 2012-04-10 21:03:56 作者: rapoo

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_valueswhere number<=len(@ret) and type='P' and substring(','+@ret,number,1)=','--------------------------APR06APR-11APR12
[解决办法]
SQL code
create function GetDistinct(@str varchar(1000))returns varchar(1000)asbegin    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 @tempendgoselect dbo.getdistinct('APR-11,APR12,APR06,APR-11,APR12,APR06')--结果:--------------------------APR-11,APR12,APR06 

读书人网 >SQL Server

热点推荐