SQL Server TRIM character

前端 未结 17 2179
感情败类
感情败类 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:43

    I've used a similar approach to some of the above answers of using pattern matching and reversing the string to find the first non-trimmable character, then cutting that off. The difference is this version does less work than those above, so should be a little more efficient.

    • This creates RTRIM functionality for any specified character.
    • It includes an additional step set @charToFind = case... to escape the chosen character.
    • There is currently an issue if @charToReplace is a right crotchet (]) as there appears to be no way to escape this.

    .

    declare @stringToSearch nvarchar(max) = '****this is****a  ** demo*****'
    , @charToFind nvarchar(5) = '*' 
    
    --escape @charToFind so it doesn't break our pattern matching
    set @charToFind = case @charToFind 
        when ']' then '[]]' --*this does not work / can't find any info on escaping right crotchet*
        when '^' then '\^'
        --when '%' then '%' --doesn't require escaping in this context
        --when '[' then '[' --doesn't require escaping in this context
        --when '_' then '_' --doesn't require escaping in this context
        else @charToFind
    end
    
    select @stringToSearch
    , left
    (
        @stringToSearch
        ,1 
        + len(@stringToSearch)
        - patindex('%[^' + @charToFind  + ']%',reverse(@stringToSearch))
    )
    

提交回复
热议问题