187

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

For example:

'TEST STRING'

to return:

'TEST STRIN'
0

24 Answers 24

217

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
3
  • 78
    Alternatively: SELECT LEFT(YourColumnName, LEN(YourColumnName) - 1) FROM YourTable
    – Kyle B.
    Commented Aug 10, 2009 at 20:05
  • 3
    Thanks for the null catch - ISNULL(LEFT(@String, LEN(@String) - 1),'ErrMsg') will solve
    – Volvox
    Commented Apr 18, 2013 at 22:57
  • 2
    @Volvox it will still throw exception if the string is Empty String, i am modifying your answer to handle this scenario. Commented Oct 14, 2015 at 14:03
133

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, ''))
4
  • 7
    Note that this code returns NULL if passed a string that is shorter than the delete range specified for STUFF. Wrap it in an ISNULL to get a different output value for the empty string case.
    – Rozwel
    Commented May 2, 2012 at 14:18
  • 14
    Nice, using this with an outer apply, with a for xml path('') to eliminate a trailing comma. awseome
    – Tracker1
    Commented Sep 27, 2012 at 19:02
  • Also the same way as @Tracker1. Unlike anything involving LEN() this gracefully works (without repeating anything) for empty string (especially wrapped in ISNULL())
    – gregmac
    Commented Jan 4, 2013 at 21:32
  • Thanks, it helped me, in my case i had a last space so the first index is 2 select reverse(stuff(reverse('a,b,c,d,'), 2, 1, ''))
    – Arngue
    Commented Jul 18, 2018 at 7:55
83

Try this:

select substring('test string', 1, len('test string') - 1)
3
  • 1
    @Adrien any idea why this seems to give the same result as select substring('test string', 0, len('test string'))? Commented Jan 23, 2013 at 6:37
  • 1
    @Louis, the substring syntax is as follows: SUBSTRING ( expression ,start , length ). Now, both queries return the same because the numbering is 1 based, meaning that the first character in the expression is 1. If start is less than 1, the returned expression will begin at the first character that is specified in expression. Source
    – JS5
    Commented Feb 12, 2019 at 17:58
  • 1
    Worked nicely in removing last 4 characters by changing the last part to - 4))
    – straville
    Commented Apr 20, 2021 at 10:02
33

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
29

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

SELECT REVERSE(SUBSTRING(REVERSE(@a), 2, 9999))
1
  • 7
    This is an Underrated comment, it's fast and it doesn't have to select the string twice to work.
    – Randall
    Commented Sep 5, 2019 at 0:18
14
select left('TEST STRING', len('TEST STRING')-1)
14

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
11
@result = substring(@result, 1, (LEN(@result)-1))
7

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

SELECT SUBSTRING(@String, 1, NULLIF(DATALENGTH(@String)-1,-1))
1
  • Also, LEN trims trailing spaces, while DATALENGTH doesn't. Commented Dec 11, 2020 at 15:22
6

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

5

I can suggest this -hack- ;).

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

SQL Server Fiddle Demo

3

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
2

Get the last character

Right(@string, len(@String) - (len(@String) - 1))
2
  • 1
    I don't think this is what he was asking, though -- this might be useful to put in a comment, however.
    – jimwise
    Commented Jan 24, 2013 at 17:02
  • 4
    just Right(@string, 1).
    – GoalBased
    Commented Apr 10, 2014 at 21:14
1

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
1

To update the record by trimming the last N characters of a particular column:

UPDATE tablename SET columnName = LEFT(columnName , LEN(columnName )-N) where clause
1

Try this

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

I encountered this problem and this way my problem was solved:

Declare @name as varchar(30)='TEST STRING'  
Select left(@name, len(@name)-1) as AfterRemoveLastCharacter 

1
0

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
1
  • You may want to use an outer/cross apply for the composite portion of the query. I'm using this to get a set of flags for a parent item.
    – Tracker1
    Commented Jan 4, 2013 at 23:01
0

Try It :

  DECLARE @String NVARCHAR(100)
    SET @String = '12354851'
    SELECT LEFT(@String, NULLIF(LEN(@String)-1,-1))
0
declare @string varchar(20)= 'TEST STRING'
Select left(@string, len(@string)-1) as Tada

output:

Tada
--------------------
TEST STRIN
1
0

Another approach, if your string @s is of a certain max size, say 10 characters.

select trim(substring(right(replicate(' ', 10) + coalesce(@s,''), 10), 1, 9))

This approach was useful when converting GTIN numbers (10 - 14 digits with a final check digit and leading 0s) to a UPC with no check digit or leading 0s:

cast(cast(SUBSTRING(RIGHT('00000' + @gtin, 14), 1, 13) as bigint) as varchar)

Examples:

  • 0012345235 --> 1234523
  • 12345678901234 --> 1234567890123
0
declare @string varchar(1000) = null
select @string =  isnull(substring (@string, 1, nullif(len(@string)-1,-1)), '')
select @string 
go

declare @string varchar(1000) = ''
select @string =  isnull(substring (@string, 1, nullif(len(@string)-1,-1)), '')
select @string 
go

declare @string varchar(1000) = '123,'
select @string =  isnull(substring (@string, 1, nullif(len(@string)-1,-1)), '')
select @string 
2
  • I guess your English is not very good since all your answers essentially contain only code. That's why they are getting down-voted. Maybe Google Translate can help you translate your explanations from your native Korean to English? (Maybe it can help to translate this comment, also.)
    – Abra
    Commented Feb 18 at 5:35
  • Please, edit and try for How to Answer, describe the effect of what you propose and why it helps to solve the problem.
    – Yunnosch
    Commented Mar 2 at 8:34
-1
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
-2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.