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

前端 未结 21 2311
不思量自难忘°
不思量自难忘° 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 09:53

    Get the last character

    Right(@string, len(@String) - (len(@String) - 1))
    
    0 讨论(0)
  • 2020-12-07 09:54

    I love @bill-hoenig 's answer; however, I was using a subquery and I got caught up because the REVERSE function needed two sets of parentheses. Took me a while to figure that one out!

    SELECT
       -- Return comma delimited list of all payment reasons for this Visit
       REVERSE(STUFF(REVERSE((
            SELECT DISTINCT
                   CAST(CONVERT(varchar, r1.CodeID) + ' - ' + c.Name + ', ' AS VARCHAR(MAX))
              FROM VisitReason r1
              LEFT JOIN ReasonCode c        ON c.ID = r1.ReasonCodeID
             WHERE p.ID = r1.PaymentID
             FOR XML PATH('')
                  )), 1, 2, ''))                        ReasonCode
      FROM Payments p
    
    0 讨论(0)
  • 2020-12-07 09:55

    This is quite late, but interestingly never mentioned yet.

    select stuff(x,len(x),1,'')
    

    ie:

    take a string x
    go to its last character
    remove one character
    add nothing
    
    0 讨论(0)
  • 2020-12-07 09:56

    If you want to do this in two steps, rather than the three of REVERSE-STUFF-REVERSE, you can have your list separator be one or two spaces. Then use RTRIM to trim the trailing spaces, and REPLACE to replace the double spaces with ','

    select REPLACE(RTRIM('a  b  c  d  '),'  ', ', ')
    

    However, this is not a good idea if your original string can contain internal spaces.

    Not sure about performance. Each REVERSE creates a new copy of the string, but STUFF is a third faster than REPLACE.

    also see this

    0 讨论(0)
  • 2020-12-07 09:57

    Try this:

    select substring('test string', 1, (len('test string') - 1))
    
    0 讨论(0)
  • 2020-12-07 09:58

    you can create function

    CREATE FUNCTION [dbo].[TRUNCRIGHT] (@string NVARCHAR(max), @len int = 1)
    RETURNS NVARCHAR(max)
    AS
    BEGIN
        IF LEN(@string)<@len
            RETURN ''
        RETURN LEFT(@string, LEN(@string) - @len)
    END
    
    0 讨论(0)
提交回复
热议问题