0

How can I make this skip duplicates?

The column may be one;two;three;two

Would like a split on ; to skip the second two (any duplicates)

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

Answer

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
2
  • What specifically do you mean by duplicates? Can't you just put a DISTINCT clause in there? Commented Dec 11, 2012 at 22:40
  • Data can be a duplicate. Will update question Commented Dec 11, 2012 at 22:42

1 Answer 1

1

Check before inserting within while loop. Add a IF NOT EXISTS as follows;

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

EDIT: Add an IF condition for checking existance

Sign up to request clarification or add additional context in comments.

1 Comment

Had to also check the final insert. I almost it had it. I was missing the NOT EXISTS. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.