sql server判斷是否重複值,sqlserver判斷重複

來源:互聯網
上載者:User

sql server判斷是否重複值,sqlserver判斷重複
一個字串為“1;2;1;1;1”。
請問:
如何在SQL SERVER中實現如下功能:
1、判斷該字串中是否存在重複的數字
如果存在重複的數字,返回錯誤資訊
如果不存在重複的數字,返回正確。


思路:分割字串,將子字串存入暫存資料表,在暫存資料表進行分組判斷

create function RepeatString(@input varchar(8000),@separator varchar(10))returns  intas begin        declare @temp table(part varchar(100))  declare @i int ,@result int set @input=rtrim(ltrim(@input))     set @i=charindex(@separator,@input)     while @i>=1     begin         insert @temp values(left(@input,@i-1))         set @input=substring(@input,@i+1,len(@input)-@i)         set @i=charindex(@separator,@input)     end     if exists(select part,count(*) from @temp group by part having count(*)>1)   set @result=1 --存在重複   else    set @result=0 --不存在重複   return   @resultendgo

--測試

select  dbo.RepeatString('1,1,2,3,1',',')  --1select  dbo.RepeatString('1,2,3,4,5',',')  --0



相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.