Removing repeated duplicated characters

后端 未结 6 1399
醉酒成梦
醉酒成梦 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:04

    Your solutions are good but

    1. it is comma only
    2. i hate loop-based TSQL code ;-)

    so i wrote based on Marcin solution set-based universal code for replacement of every declared kind of duplicates:

    DECLARE @Duplicate NVARCHAR(100)= '#$'
    DECLARE @TestString NVARCHAR(MAX)= 'test_test__f##f2$$g'
    DECLARE @Replacement NVARCHAR(MAX)= ''
    DECLARE @OutputString NVARCHAR(MAX)= @teststring ;
    WITH    numbers
              AS ( SELECT   ROW_NUMBER() OVER ( ORDER BY o.object_id, o2.object_id ) Number
                   FROM     sys.objects o
                            CROSS JOIN sys.objects o2
                 ),
            chars
              AS ( SELECT   SUBSTRING(@Duplicate, 1, 1) CHAR ,
                            CAST(1 AS INT) [LEVEL]
                   UNION ALL
                   SELECT   SUBSTRING(@Duplicate, numbers.Number, 1) CHAR ,
                            CAST(numbers.Number AS INT) [LEVEL]
                   FROM     numbers
                            JOIN chars ON chars.Level + 1 = numbers.Number
                   WHERE    LEN(SUBSTRING(@Duplicate, numbers.Number, 1)) > 0
                 ),
            Replicated
              AS ( SELECT   REPLICATE(CHAR, numbers.number) Repl ,
                            numbers.Number
                   FROM     chars
                            CROSS JOIN numbers
                 )
        SELECT  @OutputString = REPLACE(@OutputString, Repl, @Replacement)
        FROM    replicated
        WHERE   number <= LEN(@TestString)
    
    SELECT  @OutputString
    

    You can declare every kind of char in Duplicate string and every replacement string in @Replacement. Additional gain IMHO is that i search for replacement only in range of maximum length of input string

提交回复
热议问题