When developing code in TSQL, we may need to delete the last character of a string in some cases.
The other day, I used the “,” brace to combine the strings in a column. At the end, a value was generated as follows. The article name is: “How To Concatenate Query Results in SQL Server(TSQL)”
That’s why I had to delete the last character of all data in the column.
We are creating a table as follows and we are adding a few records to this table.
CREATE TABLE [dbo].[DeleteLastCharacter](
[myString] [varchar](50) NULL
) ON [PRIMARY]
INSERT INTO [dbo].[DeleteLastCharacter] VALUES('1,2,3,4,5,'),('ANKARA,ISTANBUL,IZMIR,')
When we read the data from the table, we see that the last characters are “,” as you see below.
Select * FROM [dbo].[DeleteLastCharacter]
With the help of the following script, in order to test the script, we read the data whose last characters have been deleted.
SELECT LEFT(MyString,DATALENGTH(MyString)-1) FROM [dbo].[DeleteLastCharacter]
After making sure that the script is correct, we delete the last character of the data in the column with the help of the following script.
UPDATE [dbo].[DeleteLastCharacter] SET myString=LEFT(myString,DATALENGTH(myString)-1)
SELECT * FROM [dbo].[DeleteLastCharacter]