Search code examples
sqlsql-server-2008trim

TrimEnd Equivalent in SQL Server


I have column (Numbers) which has values as follows:

1,2,3
1,2,3,
1,2,3,,,
1,2,3,,,,,,

I want to Trim all the Commas at the end of string, So that result would be

1,2,3
1,2,3
1,2,3
1,2,3

I have tried below Query but by this we can remove only one last comma

DECLARE @String as VARCHAR(50)
SET @String='1,2,3,4,,,,,,,,,,,,,,,,'

SELECT CASE WHEN right(rtrim(@String),1) = ',' then substring(rtrim(@String),1,len(rtrim(@String))-1)
    ELSE @String 
    END AS TruncString

How can I remove all the commas at the end of string?


Solution

  • You can do this using:

    LEFT(Numbers, LEN(Numbers) - (PATINDEX('%[^,]%', REVERSE(Numbers)) - 1))
    

    The premise of this is you first reverse the string using REVERSE:

    REVERSE(Numbers) --> ,,,,,,3,2,1
    

    You then find the position of the first character that is not a comma using PATINDEX and the pattern match [^,]:

    PATINDEX('%[^,]%', REVERSE(Numbers)) --> ,,,,,,3,2,1 = 7
    

    Then you can use the length of the string using LEN, to get the inverse position, i.e. if the position of the first character that is not a comma is 7 in the reversed string, and the length of the string is 10, then you need the first 4 characters of the string. You then use SUBSTRING to extract the relevant part

    A full example would be

    SELECT  Numbers,
            Reversed = REVERSE(Numbers),
            Position = PATINDEX('%[^,]%', REVERSE(Numbers)),
            TrimEnd = LEFT(Numbers, LEN(Numbers) - (PATINDEX('%[^,]%', REVERSE(Numbers)) - 1))
    FROM    (VALUES 
                ('1,2,3'), 
                ('1,2,3,'), 
                ('1,2,3,,,'), 
                ('1,2,3,,,,,,'), 
                ('1,2,3,,,5,,,'), 
                (',,1,2,3,,,5,,')
            ) t (Numbers);
    

    EDIT

    In response to an edit, that had some errors in the syntax, the below has functions to trim the start, and trim both sides of commas:

    SELECT  Numbers,
            Reversed = REVERSE(Numbers),
            Position = PATINDEX('%[^,]%', REVERSE(Numbers)),
            TrimEnd = LEFT(Numbers, LEN(Numbers) - (PATINDEX('%[^,]%', REVERSE(Numbers)) - 1)),
            TrimStart = SUBSTRING(Numbers, PATINDEX('%[^,]%', Numbers), LEN(Numbers)),
            TrimBothSide = SUBSTRING(Numbers, 
                                        PATINDEX('%[^,]%', Numbers), 
                                        LEN(Numbers) - 
                                            (PATINDEX('%[^,]%', REVERSE(Numbers)) - 1) - 
                                            (PATINDEX('%[^,]%', Numbers) - 1)
                                        )
    FROM    (VALUES 
                ('1,2,3'), 
                ('1,2,3,'), 
                ('1,2,3,,,'), 
                ('1,2,3,,,,,,'), 
                ('1,2,3,,,5,,,'), 
                (',,1,2,3,,,5,,')
            ) t (Numbers);