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

前端 未结 21 2314
不思量自难忘°
不思量自难忘° 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:00
    select left('TEST STRING', len('TEST STRING')-1)
    
    0 讨论(0)
  • 2020-12-07 10:00

    If your coloumn is text and not varchar, then you can use this:

    SELECT SUBSTRING(@String, 1, NULLIF(DATALENGTH(@String)-1,-1))
    
    0 讨论(0)
  • 2020-12-07 10:00

    Try this,

    DECLARE @name NVARCHAR(MAX) SET @name='xxxxTHAMIZHMANI****'SELECT Substring(@name, 5, (len(@name)-8)) as UserNames
    

    And the output will be like, THAMIZHMANI

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

    This will work even when source text/var is null or empty:

    SELECT REVERSE(SUBSTRING(REVERSE(@a), 2, 9999))
    
    0 讨论(0)
  • 2020-12-07 10:04
    declare @string varchar(20)= 'TEST STRING'
    Select left(@string, len(@string)-1) as Tada
    

    output:

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

    If for some reason your column logic is complex (case when ... then ... else ... end), then the above solutions causes you to have to repeat the same logic in the len() function. Duplicating the same logic becomes a mess. If this is the case then this is a solution worth noting. This example gets rid of the last unwanted comma. I finally found a use for the REVERSE function.

    select reverse(stuff(reverse('a,b,c,d,'), 1, 1, ''))
    
    0 讨论(0)
提交回复
热议问题