You are hereBlogs / rahul's blog / Trimming a custom character from the end of a T-Sql string

Trimming a custom character from the end of a T-Sql string


rahul's picture

By rahul - Posted on 03 January 2010

I recently had a situation where I needed to trim a custom character from the right of a string in Sql Server. Although Sql Server provides a RTRIM function, it can only trim spaces from a string.

A quick search over web threw up some interesting results, but all of them were buggy in one way or another. The major problem was that most of them assumed that spaces would not occur in the string itself.

So, I came up with the following solution as a UDF:

    CREATE FUNCTION [dbo].[RTrimChar]
    (
        @input nvarchar(MAX),
        @trimChar nchar(1)
    )
    RETURNS nvarchar(MAX)
    AS
    BEGIN
    DECLARE @len int, @index int;
        
        set @len = LEN(@input);
        set @input = REVERSE(@input);
        set @index = PATINDEX('%[^' + @trimChar + ']%', @input);
        
        IF @index = 0
            set @input = ''
        ELSE
            set @input = REVERSE(SUBSTRING(@input, @index, @len));
            
        RETURN @input;
    END
    GO

    SELECT [CRC1].[dbo].[RTrimChar] (
       'Sample // String //',
      '/');
    GO

I would like to know if anyone faces any issues with the above solution for trimming any custom charcater from the right of an Sql string. It can be modified easily to do the same from the left of a string.

Post new comment

The content of this field is kept private and will not be shown publicly.

Mollom CAPTCHA (play audio CAPTCHA)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.