Skip to content
Advertisement

SQL : remove last comma in string

I have a text memo field in SQL table that I need to remove the last character in the field if it’s a comma.

So, for example, if I have these rows, I need to remove the commas from rows 2 and 4.

The output would be:

Any ideas?

Advertisement

Answer

Using REVERSE and STUFF:


First, you want to TRIM your data to get rid of leading and trailing spaces. Then REVERSE it and check if the first character is ,. If it is, remove it, otherwise do nothing. Then REVERSE it back again. You can remove the first character by using STUFF(string, 1, 1, '').

SQL Fiddle

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement