SQL Server TRIM character

前端 未结 17 2152
感情败类
感情败类 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
    LEFT('BOB*', LEN('BOB*')-1)
    

    should do it.

    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-12-09 17:24

    If you wanted behavior similar to how RTRIM handles spaces i.e. that "B*O*B**" would turn into "B*O*B" without losing the embedded ones then something like -

    REVERSE(SUBSTRING(REVERSE('B*O*B**'), PATINDEX('%[^*]%',REVERSE('B*O*B**')), LEN('B*O*B**') - PATINDEX('%[^*]%', REVERSE('B*O*B**')) + 1))
    

    Should do it.

    0 讨论(0)
  • 2020-12-09 17:25

    @teejay solution is great. But the code below can be more understandable:

    declare @X nvarchar(max)='BOB *'
    
    set @X=replace(@X,' ','^')
    
    set @X=replace(@X,'*',' ')
    
    set @X= ltrim(rtrim(@X))
    
    set @X=replace(@X,'^',' ')
    
    0 讨论(0)
  • 2020-12-09 17:27

    SqlServer2017 has a new way to do it: https://docs.microsoft.com/en-us/sql/t-sql/functions/trim-transact-sql?view=sql-server-2017

    SELECT TRIM('0' FROM '00001900'); -> 19

    SELECT TRIM( '.,! ' FROM '# test .'); -> # test

    SELECT TRIM('*' FROM 'BOB*'); --> BOB

    Unfortunately, RTRIM does not support trimming a specific character.

    0 讨论(0)
  • 2020-12-09 17:32
        SELECT REPLACE('BOB*', '*', '')  
        SELECT REPLACE('B*OB*', '*', '') 
    -------------------------------------
         Result : BOB
    -------------------------------------
    

    this will replace all asterisk* from the text

    0 讨论(0)
提交回复
热议问题