Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Replace multiple different characters in string

I need to replace multiple characters in a string. The result can't contain any '&' or any commas.

I currently have:

REPLACE(T2.[ShipToCode],'&','and') 

But how do you put multiple values in?

Many thanks!

like image 473
coblenski Avatar asked Aug 30 '16 15:08

coblenski


People also ask

How do I replace multiple characters in a string in SQL?

If you wanted to replace the words with blank string, go with REGEXP_REPLACE() . If you want to replace the words with other words, for example replacing & with and then use replace() . If there are multiple words to be replaced, use multiple nested replace() .

Can we replace multiple values in SQL?

Using the REPLACE() function will allow you to change a single character or multiple values within a string, whether working to SELECT or UPDATE data.

How do you replace multiple characters?

If you want to replace multiple characters you can call the String. prototype. replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping that you will use in that function.

How do I change the first 3 characters in SQL?

In a view, you could do it like: select case when col1 like '00%' then stuff(col1, 1, 2, '11') else col1 end from YourTable; Live example at SQL Fiddle. Just a note, the substring should be "substring(col1, 3, len(col1)-2)"because you want to start at 3rd character and the characters are numbered from 1, not 0.


2 Answers

You just need to daisy-chain them:

REPLACE(REPLACE(T2.[ShipToCode], '&', 'and'), ',', '') 
like image 196
Siyual Avatar answered Sep 21 '22 17:09

Siyual


One comment mentions "dozens of replace calls"... if removing dozens of single characters, you could also use Translate and a single Replace.

REPLACE(TRANSLATE(T2.[ShipToCode], '[];'',$@', '#######'), '#', '') 
like image 33
CLaFarge Avatar answered Sep 19 '22 17:09

CLaFarge