SQL Replace multiple different characters in string SQL Replace multiple different characters in string sql sql

SQL Replace multiple different characters in string


You just need to daisy-chain them:

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


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], '[];'',$@', '#######'), '#', '')


We used a function to do something similar that looped through the string, though this was mostly to remove characters that were not in the "@ValidCharacters" string. That was useful for removing anything that we didn't want - usually non-alphanumeric characters, though I think we also had space, quote, single quote and a handful of others in that string. It was really used to remove the non-printing characters that tended to sneak in at times so may not be perfect for your case, but may give you some ideas.

CREATE FUNCTION [dbo].[ufn_RemoveInvalidCharacters] (@str VARCHAR(8000), @ValidCharacters VARCHAR(8000))RETURNS VARCHAR(8000)BEGIN  WHILE PATINDEX('%[^' + @ValidCharacters + ']%',@str) > 0   SET @str=REPLACE(@str, SUBSTRING(@str ,PATINDEX('%[^' + @ValidCharacters +']%',@str), 1) ,'')  RETURN @strEND