字符串重复值过滤
-- ======================================== -- Author:<Oliver QIN> -- Date :<2016/01/13> -- Desc :<过滤重复字符> -- ======================================== --类型一: IF OBJECT_ID('DBO.DISTINCT_STR') IS NOT NULL DROP FUNCTION DBO.DISTINCT_STR GO CREATE FUNCTION DBO.DISTINCT_STR(@str NVARCHAR(100),@SPLIT VARCHAR(50)) RETURNS VARCHAR(100) AS BEGIN ---------------------------------------如果输入的字符则返回空值 IF @str IS NULL RETURN(NULL) DECLARE @NEW VARCHAR(50),@INDEX INT,@TEMP VARCHAR(50) IF LEFT(@str,1)<>@SPLIT SET @str = @SPLIT+@str IF RIGHT(@str,1)<>@SPLIT SET @str = @str+@SPLIT WHILE CHARINDEX(@SPLIT,@str)>0 AND LEN(@str)<>1 BEGIN SET @INDEX = CHARINDEX(@SPLIT,@str) SET @TEMP = LEFT(@str,CHARINDEX(@SPLIT,@str,@INDEX+LEN(@SPLIT))) IF @NEW IS NULL SET @NEW = ISNULL(@NEW,'')+@TEMP ELSE SET @NEW = ISNULL(@NEW,'')+REPLACE(@TEMP,@SPLIT,'')+@SPLIT WHILE CHARINDEX(@TEMP,@str)>0 BEGIN SET @str=STUFF(@str,CHARINDEX(@TEMP,@str)+LEN(@SPLIT),CHARINDEX(@SPLIT,@str,CHARINDEX(@TEMP,@str)+LEN(@SPLIT))-CHARINDEX(@TEMP,@str),'') END END RETURN RIGHT(LEFT(@NEW,LEN(@NEW)-1),LEN(LEFT(@NEW,LEN(@NEW)-1))-1) END GO PRINT DBO.DISTINCT_STR('张三,A,B,C,CB,张三,C,',',') ------------------------------------------------- ----类型二: IF OBJECT_ID('DBO.DISTINCT_STR2') IS NOT NULL DROP FUNCTION DBO.DISTINCT_STR2 GO CREATE FUNCTION DBO.DISTINCT_STR2(@S varchar(8000)) RETURNS VARCHAR(100) AS BEGIN IF @S IS NULL RETURN(NULL) DECLARE @NEW VARCHAR(50),@INDEX INT,@TEMP VARCHAR(50) WHILE LEN(@S)>0 BEGIN SET @NEW=ISNULL(@NEW,'')+LEFT(@S,1) SET @S=REPLACE(@S,LEFT(@S,1),'') END RETURN @NEW END GO SELECT DBO.DISTINCT_STR2('AABCCD') --ABCD GO -------------------------------------------------------------------- --获取字符串中指定的字符 IF OBJECT_ID('DBO.SPLIT_STR') IS NOT NULL DROP FUNCTION DBO.SPLIT_STR GO CREATE FUNCTION DBO.SPLIT_STR( @S varchar(8000), --包含多个数据项的字符串 @INDEX int, --要获取的数据项的位置 @SPLIT varchar(10) --数据分隔符 ) RETURNS VARCHAR(100) AS BEGIN IF @S IS NULL RETURN(NULL) DECLARE @SPLITLEN int SELECT @SPLITLEN=LEN(@SPLIT+'A')-2 WHILE @INDEX>1 AND CHARINDEX(@SPLIT,@S+@SPLIT)>0 SELECT @INDEX=@INDEX-1,@S=STUFF(@S,1,CHARINDEX(@SPLIT,@S+@SPLIT)+@SPLITLEN,'') RETURN(ISNULL(LEFT(@S,CHARINDEX(@SPLIT,@S+@SPLIT)-1),'')) END GO PRINT DBO.SPLIT_STR('AA|BB|CC',2,'|') -- GO
作者:奔跑的金鱼
声明:书写博客不易,转载请注明出处,请支持原创,侵权将追究法律责任
个性签名:人的一切的痛苦,本质上都是对自己无能的愤怒
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!