Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace first and last character of column in sql server?

I have a database column and its give a string like ,Recovery, Pump Exchange,.

I want remove first and last comma from string.

Expected Result : Recovery, Pump Exchange.

like image 761
Manish Sharma Avatar asked Mar 12 '14 13:03

Manish Sharma


People also ask

How do I remove the first 2 characters in sql?

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

How can I remove last character from a string in sql?

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 get the last character of a column in SQL Server?

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.


1 Answers

You can use SUBSTRING for that:

SELECT
    SUBSTRING(col, 2, LEN(col)-2)
FROM ...

Obviously, an even better approach would be not to put leading and trailing commas there in the first place, if this is an option.

I want to remove last and first comma only if exist otherwise not.

The expression becomes a little more complex, but the idea remains the same:

SELECT SUBSTRING(
    col
,  CASE LEFT(@col,1) WHEN ',' THEN 2 ELSE 1 END
,  LEN(@col) -- Start with the full length
             -- Subtract 1 for comma on the left
      - CASE LEFT(@col,1) WHEN ',' THEN 1 ELSE 0 END 
             -- Subtract 1 for comma on the right
      - CASE RIGHT(@col,1) WHEN ',' THEN 1 ELSE 0 END
)
FROM ...
like image 174
Sergey Kalinichenko Avatar answered Sep 22 '22 15:09

Sergey Kalinichenko