Escaping ] and ^ characters in a T-SQL “pattern” expression character class

后端 未结 2 693
滥情空心
滥情空心 2021-01-20 19:40

I\'m trying to emulate Oracle\'s RTRIM(expression, characters) in MsSql Server 2008 R2 with the following query:

REVERSE(
        SUBSTRING(
            


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-20 20:14

    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
    

提交回复
热议问题