0

我怎样才能让这个跳过重复?

列可以是一;二;三;二

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

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
4

1 回答 1

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 条件来检查存在

于 2012-12-11T22:46:56.973 回答