字符串重复值过滤

-- ========================================
-- 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

 

posted @ 2016-01-13 15:37  OLIVER_QIN  阅读(821)  评论(0编辑  收藏  举报