Remove the last character in a string in T-SQL?

前端 未结 21 2313
不思量自难忘°
不思量自难忘° 2020-12-07 09:22

How do I remove the last character in a string in T-SQL?

For example:

\'TEST STRING\'

to return:

\'TES         


        
相关标签:
21条回答
  • 2020-12-07 10:09
    declare @x varchar(20),@y varchar(20)
    select @x='sam'
    select 
    case when @x is null then @y
          when @y is null then @x
          else @x+','+@y
    end
    
    
    go
    
    declare @x varchar(20),@y varchar(20)
    select @x='sam'
    --,@y='john'
    DECLARE @listStr VARCHAR(MAX)   
    
    SELECT @listStr = COALESCE(@x + ', ' ,'') +coalesce(@y+',','')
    SELECT left(@listStr,len(@listStr)-1)
    
    0 讨论(0)
  • 2020-12-07 10:12

    If your string is empty,

    DECLARE @String VARCHAR(100)
    SET @String = ''
    SELECT LEFT(@String, LEN(@String) - 1)
    

    then this code will cause error message 'Invalid length parameter passed to the substring function.'

    You can handle it this way:

    SELECT LEFT(@String, NULLIF(LEN(@String)-1,-1))
    

    It will always return result, and NULL in case of empty string.

    0 讨论(0)
  • 2020-12-07 10:12

    Try It :

      DECLARE @String NVARCHAR(100)
        SET @String = '12354851'
        SELECT LEFT(@String, NULLIF(LEN(@String)-1,-1))
    
    0 讨论(0)
  • 2020-12-07 10:13

    e.g.

    DECLARE @String VARCHAR(100)
    SET @String = 'TEST STRING'
    
    -- Chop off the end character
    SET @String = 
         CASE @String WHEN null THEN null 
         ELSE (
             CASE LEN(@String) WHEN 0 THEN @String 
                ELSE LEFT(@String, LEN(@String) - 1) 
             END 
         ) END
    
    
    SELECT @String
    
    0 讨论(0)
  • 2020-12-07 10:13

    My answer is similar to the accepted answer, but it also check for Null and Empty String.

    DECLARE @String VARCHAR(100)
    
    SET @String = 'asdfsdf1'
    
    -- If string is null return null, else if string is empty return as it is, else chop off the end character
    SET @String = Case @String when null then null else (case LEN(@String) when 0 then @String else LEFT(@String, LEN(@String) - 1) end ) end
    
    SELECT @String
    
    0 讨论(0)
  • 2020-12-07 10:14

    I can suggest this -hack- ;).

    select 
        left(txt, abs(len(txt + ',') - 2))
    from 
        t;
    

    SQL Server Fiddle Demo

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