Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing characters in a string based on rows in a table sql

I need to replace a list of characters in a string with some mapped characters.

I have a table 'dbo.CharacterMappings' with 2 columns: 'CharacterToFilter' and 'ReplacementCharacter'.

Say that there are 3 records in this table:

Filter   Replacement    
$        s
@        a
0        o

How would I replace all of the filter characters in a string based on these mappings?

i.e. 'Hell0 c@t$' needs to become 'Hello cats'.

I cant really think of any way of doing this without resorting to a table variable and then looping through it. I.e. have a table variable with a 'count' column then use a loop to select 1 row at a time based on this column. Then I can use the REPLACE function to update the characters one at a time.

Edit: I should note that I always want to strip out these characters (I don't need to worry about $5 -> s5 for example).

like image 733
RobH Avatar asked Oct 24 '12 14:10

RobH


People also ask

How do I replace a character in a string in SQL?

SQL Server REPLACE() Function The REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: The search is case-insensitive.

How do I replace multiple characters in a string 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.


2 Answers

declare @s varchar(50)= 'Hell0 c@t$'
select @s = REPLACE(@s, CharacterToFilter, ReplacementCharacter) 
    from CharacterMappings
select @s
like image 66
podiluska Avatar answered Oct 24 '22 02:10

podiluska


You could create a function:

CREATE FUNCTION [dbo].[ReplaceAll]
(
    @text varchar(8000)
)
RETURNS VARCHAR(8000)
AS
BEGIN
    SELECT @text = 
       REPLACE(@text,cm.Filter, cm.Replacement)
    FROM    CharacterMappings cm;
    RETURN @text
END

Then this

select dbo.[ReplaceAll]('Hell0 c@t$');

returns Hello cats

like image 21
Tim Schmelter Avatar answered Oct 24 '22 02:10

Tim Schmelter