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

Viewed 519675

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

For example:

'TEST STRING'

to return:

'TEST STRIN'
22 Answers

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

Try this:

select substring('test string', 1, (len('test string') - 1))

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

SELECT REVERSE(SUBSTRING(REVERSE(@a), 2, 9999))

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

Try this

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

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 

Related