2012-12-11 100 views
0

如何使這個跳過重複?TSQL分割功能跳過重複

該柱可以是 一個;二;三;二

想上的分裂; while循環中插入前要跳過所述第二兩(任何重複)

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 
+0

明確你通過重複的意思的IF條件?你不能只在這裏放置一個DISTINCT子句嗎? – Neil

+0

數據可能是重複的。將更新問題 – Paparazzi

回答

1

檢查。如下添加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 

編輯:添加用於檢查所有腦幹

+0

這看起來應該起作用。 – Neil

+0

還必須檢查最終插入。我幾乎擁有它。我錯過了NOT EXISTS。謝謝 – Paparazzi