TSQL分割功能跳过重复

时间:2012-12-11 22:26:46

标签: sql-server-2008 tsql

如何将此跳过重复?

列可能是 一个;二;三;二

想分开;跳过后两个(任何重复)

CREATE FUNCTION dbo.Split2
(
    @RowData varchar(max),
    @SplitOn varchar(5)
)  
RETURNS @RtnValue table 
(
    Id int identity(1,1),
    Data varchar(8000)
) 
AS  
BEGIN 
    Declare @Cnt int
    Set @Cnt = 1

    While (Charindex(@SplitOn,@RowData)>0)
    Begin
        Insert Into @RtnValue (data)
        Select 
            Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1
    End

    Insert Into @RtnValue (data)
    Select Data = ltrim(rtrim(@RowData))

    Return
END

回答

CREATE FUNCTION dbo.Split2
(
    @RowData varchar(max),
    @SplitOn varchar(5)
)  
RETURNS @RtnValue table 
(
    Id int identity(1,1),
    Data varchar(8000)
) 
AS  
BEGIN 
    Declare @Data varchar(8000)
    Declare @Cnt int
    Set @Cnt = 1 

    While (Charindex(@SplitOn,@RowData)>0)
    Begin
        set @Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
        IF NOT EXISTS (SELECT * FROM @RtnValue WHERE data = @Data) 
        BEGIN
           INSERT INTO @RtnValue (data)
           VALUES (@Data)
        END
        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1
    End
    set @Data = ltrim(rtrim(@RowData))
    IF NOT EXISTS (SELECT * FROM @RtnValue WHERE data = @Data) 
    BEGIN
       INSERT INTO @RtnValue (data)
       VALUES (@Data)
    END

    Return
END

1 个答案:

答案 0 :(得分:1)

在插入while循环之前检查。添加IF NOT EXISTS,如下所示;

DECLARE @temp VARCHAR(100) --declare a temp variable

While (Charindex(@SplitOn,@RowData)>0)
Begin

   SELECT @temp = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

   IF NOT EXISTS (SELECT * FROM @RtnValue WHERE data = @temp) 
   BEGIN
       INSERT INTO @RtnValue (data)
       VALUES (@temp)
   END

   Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
   Set @Cnt = @Cnt + 1
End

编辑:添加用于检查存在的IF条件