• _ms65g_ (5/28/2010)


    Remove duplicate side-by-side characters from a string

    New approach using numbers table

    CREATE FUNCTION dbo.fnRemoveDupesI (@String VARCHAR(8000)) 

    RETURNS VARCHAR(8000) 

    AS

    BEGIN

        DECLARE @result VARCHAR(8000) = '';

       

       ;WITH DataOrder

       AS

       (

          SELECT ID, Data

                 ,ROW_NUMBER() OVER (PARTITION BY Data ORDER BY ID) AS RowNum

            FROM (SELECT SUBSTRING(@String, nbr, 1), nbr 

                    FROM Nums 

                   WHERE nbr <= LEN(@String)

                 ) D(data, ID)

       )

      

      SELECT @result = @result + Data

        FROM (SELECT ID, Data

                     ,DENSE_RANK() OVER (ORDER BY ID - RowNum) As [Rank]

                FROM DataOrder

             )D

       GROUP BY Data, [Rank]

       ORDER BY MIN(ID)

       RETURN @result

    END;

    Be careful with the multirow concatenation thing you got going on there. You might be better off using the FOR XML PATH subquery method for ordered string concatenation (but then you have to worry about XML entities).

    Thanks

    Mike C