Removing repeated duplicated characters

后端 未结 6 1427
醉酒成梦
醉酒成梦 2021-02-08 12:12

I have a string in my stored proc like \',,,sam,,bob,\' or \',,,\' from the above string I have to delete multiple commas from it, it must look like <

6条回答
  •  时光取名叫无心
    2021-02-08 13:01

    I would suggest a UDF to do this. Since the UDF I am about to suggest doesn't touch any tables, the performance should be pretty good.

    CREATE Function [dbo].[CleanDuplicates](@Data VarChar(8000), @DuplicateChar VarChar(1))
    Returns VarChar(8000)
    WITH SCHEMABINDING
    AS
    Begin
    
        Set @Data = @DuplicateChar + @Data
    
        While PATINDEX('%' + @DuplicateChar + @DuplicateChar + '%',@Data) > 0
            Set @Data = REPLACE(@Data, @DuplicateChar + @DuplicateChar,@DuplicateChar)
    
        Return Right(@Data, Len(@Data)-1)
    
    End
    

    You can test the function like this:

    Select dbo.CleanDuplicates(',,,', ',')
    Select dbo.CleanDuplicates(',,,sam,,bob,', ',')
    

提交回复
热议问题