SQL Server TRIM character

前端 未结 17 2173
感情败类
感情败类 2020-12-09 17:11

I have the following string: \'BOB*\', how do I trim the * so it shows up as \'BOB\'

I tried the RTRIM(\'BOB*\',\'*\') but does not work as says needs only 1 paramet

17条回答
  •  抹茶落季
    2020-12-09 17:22

    CREATE FUNCTION dbo.TrimCharacter
    (
        @Value NVARCHAR(4000),
        @CharacterToTrim NVARCHAR(1)
    )
    RETURNS NVARCHAR(4000)
    AS
    BEGIN
        SET @Value = LTRIM(RTRIM(@Value))
        SET @Value = REVERSE(SUBSTRING(@Value, PATINDEX('%[^'+@CharacterToTrim+']%', @Value), LEN(@Value)))
        SET @Value = REVERSE(SUBSTRING(@Value, PATINDEX('%[^'+@CharacterToTrim+']%', @Value), LEN(@Value)))
        RETURN @Value
    END
    GO
    --- Example
    ----- SELECT dbo.TrimCharacter('***BOB*********', '*')
    ----- returns 'BOB'
    

提交回复
热议问题