Daveed
Daveed

Reputation: 1921

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

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

For example:

'TEST STRING'

to return:

'TEST STRIN'

Upvotes: 190

Views: 612042

Answers (25)

Bill Hall
Bill Hall

Reputation: 121

Perhaps I missed it above, but none of the answers above seem to verify that you actually want to remove the last character. Though some account for NULL or empty strings, they all just assume the comma, or whatever char you are removing, is present in all cases.

DECLARE @test VARCHAR(20)  = 'CA,NV,TN,FL,'  -- 'CA,NV,TN,FL'

SELECT 
    CASE WHEN CHARINDEX(',',REVERSE(@test)) = 1 
         THEN SUBSTRING(@test, 1, len(@test) - 1)
         ELSE @test
    END AS Fixed

Upvotes: 0

Adrien
Adrien

Reputation: 3205

Try this:

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

Upvotes: 84

김민석
김민석

Reputation: 1

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 

Upvotes: 0

Glen Little
Glen Little

Reputation: 7148

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

Upvotes: 0

mohsen mashhadi
mohsen mashhadi

Reputation: 283

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 

Upvotes: 1

David Roach
David Roach

Reputation: 341

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

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

Upvotes: 29

George Menoutis
George Menoutis

Reputation: 7260

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

Upvotes: 14

shA.t
shA.t

Reputation: 16968

I can suggest this -hack- ;).

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

SQL Server Fiddle Demo

Upvotes: 5

Sam
Sam

Reputation: 29

Get the last character

Right(@string, len(@String) - (len(@String) - 1))

Upvotes: 2

Farrukh Saleem Sheikh
Farrukh Saleem Sheikh

Reputation: 117

@result = substring(@result, 1, (LEN(@result)-1))

Upvotes: 11

Thamizhmani
Thamizhmani

Reputation: 3

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

Upvotes: -3

Abhishek Jaiswal
Abhishek Jaiswal

Reputation: 1249

Try this

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

Upvotes: 1

AdaTheDev
AdaTheDev

Reputation: 147354

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

Upvotes: 218

greg121
greg121

Reputation: 964

select left('TEST STRING', len('TEST STRING')-1)

Upvotes: 14

Migo
Migo

Reputation: 151

declare @string varchar(20)= 'TEST STRING'
Select left(@string, len(@string)-1) as Tada

output:

Tada
--------------------
TEST STRIN

Upvotes: 0

Chilli
Chilli

Reputation: 123

Try It :

  DECLARE @String NVARCHAR(100)
    SET @String = '12354851'
    SELECT LEFT(@String, NULLIF(LEN(@String)-1,-1))

Upvotes: 0

Manvendra_0611
Manvendra_0611

Reputation: 146

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

Upvotes: 1

Imran Rizvi
Imran Rizvi

Reputation: 7438

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

Upvotes: 1

Mihail Katrikh
Mihail Katrikh

Reputation: 141

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

Upvotes: 3

Julie
Julie

Reputation: 11

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)

Upvotes: -1

PonyTricks
PonyTricks

Reputation: 1798

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

SELECT SUBSTRING(@String, 1, NULLIF(DATALENGTH(@String)-1,-1))

Upvotes: 7

Daryl
Daryl

Reputation: 69

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

Upvotes: 6

hurleystylee
hurleystylee

Reputation: 612

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

Upvotes: 0

Maxim Grachev
Maxim Grachev

Reputation: 439

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.

Upvotes: 33

Bill Hoenig
Bill Hoenig

Reputation: 1341

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, ''))

Upvotes: 134

Related Questions