How do I remove the last character in a string in T-SQL
?
For example:
\'TEST STRING\'
to return:
\'TES
select left('TEST STRING', len('TEST STRING')-1)
If your coloumn is text
and not varchar
, then you can use this:
SELECT SUBSTRING(@String, 1, NULLIF(DATALENGTH(@String)-1,-1))
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
This will work even when source text/var is null or empty:
SELECT REVERSE(SUBSTRING(REVERSE(@a), 2, 9999))
declare @string varchar(20)= 'TEST STRING'
Select left(@string, len(@string)-1) as Tada
output:
Tada
--------------------
TEST STRIN
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, ''))