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)”
1 |
1,2,3,4,5, |
That’s why I had to delete the last character of all data in the column.
Example:
We are creating a table as follows and we are adding a few records to this table.
1 2 3 4 5 |
CREATE TABLE [dbo].[DeleteLastCharacter]( [myString] [varchar](50) NULL ) ON [PRIMARY] GO 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.
1 |
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.
1 |
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.
1 2 3 |
UPDATE [dbo].[DeleteLastCharacter] SET myString=LEFT(myString,DATALENGTH(myString)-1) GO SELECT * FROM [dbo].[DeleteLastCharacter] |