I\'m trying to emulate Oracle\'s RTRIM(expression, characters)
in MsSql Server 2008 R2 with the following query:
REVERSE(
SUBSTRING(
Not pretty, but...
CREATE FUNCTION dbo.RTRIMCHARS(
@input AS VARCHAR(MAX), @chars AS VARCHAR(100)
) RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @charpos BIGINT
DECLARE @strpos BIGINT
SET @strpos = LEN(@input)
SET @charpos = LEN(@chars)
IF @strpos IS NULL OR @charpos IS NULL RETURN NULL
IF @strpos = 0 OR @charpos = 0 RETURN @input
WHILE @strpos > 0
BEGIN
SET @charpos = LEN(@chars)
WHILE @charpos > 0
BEGIN
IF SUBSTRING(@chars, @charpos, 1) = SUBSTRING(@input, @strpos, 1)
BEGIN
SET @strpos = @strpos - 1
BREAK
END
ELSE
BEGIN
SET @charpos = @charpos - 1
END
END
IF @charpos = 0 BREAK
END
RETURN SUBSTRING(@input, 1, @strpos)
END
Usage
SELECT dbo.RTRIMCHARS('bla%123', '123%') -- 'bla'
SELECT dbo.RTRIMCHARS('bla%123', '123') -- 'bla%'
SELECT dbo.RTRIMCHARS('bla%123', 'xyz') -- 'bla%123'
SELECT dbo.RTRIMCHARS('bla%123', ']') -- 'bla%123'
SELECT dbo.RTRIMCHARS('bla%123', '') -- 'bla%123'
SELECT dbo.RTRIMCHARS('bla%123', NULL) -- NULL
SELECT dbo.RTRIMCHARS(NULL, '123') -- NULL