Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete last N characters from field in a SQL Server database

Tags:

sql-server

I have table of over 4 million rows and accidentally in one column there is more data than needed.

For example instead of ABC there is ABC DEFG.

How can I remove that N symbols using TSQL? Please note that I want to delete this characters from database, NOT just select substring. Thank you

like image 816
seeker Avatar asked May 06 '12 12:05

seeker


People also ask

How can I remove last 4 characters from a string in SQL?

Syntax: SELECT SUBSTRING(column_name,1,length(column_name)-N) FROM table_name; Example: Delete the last 2 characters from the FIRSTNAME column from the geeksforgeeks table.

How do I delete a trailing character in SQL?

SQL Server TRIM() Function The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string.

How do I get last 5 characters of a string in SQL?

To get the first n characters of string with MySQL, use LEFT(). To get the last n char of string, the RIGHT() method is used in MySQL.

How do I remove a character from a column in SQL?

Syntax: SELECT SUBSTRING(column_name,2,length(column_name)) FROM table_name; To delete the first character from the FIRSTNAME column from the geeks for geeks table.


2 Answers

UPDATE mytable SET column=LEFT(column, LEN(column)-5) 

Removes the last 5 characters from the column (every row in mytable)

like image 107
erikxiv Avatar answered Nov 06 '22 15:11

erikxiv


I got the answer to my own question, ant this is:

select reverse(stuff(reverse('a,b,c,d,'), 1, N, '')) 

Where N is the number of characters to remove. This avoids to write the complex column/string twice

like image 35
Fernando Torres Avatar answered Nov 06 '22 14:11

Fernando Torres