Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Take off last character if a certain one exists in a string

I have a column with few different ID's

abc_1234
abc_2345
bcd_3456/
cde_4567/

And I want a new column that takes off the / if it exists

abc_1234
abc_2345
bcd_3456
cde_4567

I know I'll be using a combination of IF/THEN, LEFT, and LEN, but I don't know the syntax. Help is appreciated! Thanks!

like image 544
Takeshi Tawarada Avatar asked May 05 '15 14:05

Takeshi Tawarada


People also ask

How do I get the last character of a string in a substring 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 specific character from a string in SQL?

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. Note: Also look at the LTRIM() and RTRIM() functions.

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

Below is the syntax for the SUBSTRING() function to delete the last N characters from the field. 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 remove one character from the left in SQL?

To delete the first characters from the field we will use the following query: Syntax: SELECT SUBSTRING(string, 2, length(string));


2 Answers

(In case your are using SQL Server RDBMS)

You can try the following combination of right and left:

case when right(col, 1) = '/' then left(col, len(col)-1) else col end

SQLFiddle

(In case your are using MySQL RDBMS)

trim(trailing '/' from col);

SQLFiddle

like image 103
potashin Avatar answered Sep 20 '22 20:09

potashin


If your using SQL Server try this

SELECT REPLACE(col,'/','')

Replace (Transact-SQL)

like image 30
Nate S. Avatar answered Sep 17 '22 20:09

Nate S.