6

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).

2 Answers 2

12
declare @s varchar(50)= 'Hell0 c@t$'
select @s = REPLACE(@s, CharacterToFilter, ReplacementCharacter) 
    from CharacterMappings
select @s
Sign up to request clarification or add additional context in comments.

3 Comments

Wow, thanks. I didn't know/have never seen REPLACE used like that!
That would only work in a function or stored procedure, but it's still pretty slick.
@LittleBobbyTables with a couple of semi-colons, I think you could use it from anywhere?
8

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

2 Comments

The code is going to be part of a function anyway but thanks for pointing it out.
Thanks Tim, this helped me build a large text search replace. Saved my time too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.