Programming Solutions

Your Source for Information

Removing the last character from a TSQL string

by Maeenul 29. March 2011 09:51

Often we need to remove the last few characters from a tsql string. To remove last n characters from a tsql string we may apply any of the below methods.

Method 1: Removing the last character from tsql string using LEFT()

DECLARE @String VARCHAR(100)

SET @String = 'TEST STRING'

SET @String = LEFT(@String, LEN(@String) - 1)

SELECT @String

Left function returns the n characters starting from the leftmost position of the string. So we can first find the length of the string and then take one less character than the total length.

Method 2: Removing the last character from tsql string using SUBSTRING()

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

Using substring, we can take the length-1 characters from the starting position. For substring function, 1 is considered the starting position.

Method 3: Removing the last character from tsql string using STUFF()

DECLARE @String VARCHAR(100
SET @String = 'TEST STRING'
SET @String = STUFF(@String, LEN(@String), 1, '') 
SELECT @String 

The second parameter of the stuff function is the starting position for stuffing, the third parameter means how many characters will be stuffed and the forth parameter means which character to use for stuffing. Here we need to stuff 1 character from the last position with a blank string.

Tags:

Category: TSQL



Add comment

biuquote
  • Comment
  • Preview
Loading

Alpha Tags