Disclaimer: the function is smoothed, as promised, will timely update the description of the response.
In accordance with my current understanding of your problem, I think I can apply a function to it that I developed to solve a more complex problem that I recently had. There may be other solutions, but, of course, others can and will offer them, so why not offer me something less that can be offered.
Be careful, however, it was intended to solve something more complex than yours (explained later), and now, unfortunately, I do not have time to shorten it, but I will get to that, probably tomorrow. I hope the comments help. To no avail, I will summarize my function for you:
Here is a table that contains the messages that need to be found, and what to replace them with. The function will receive a text value as an input signal, will use the cursor to cycle the specified table, and for each record in the specified table it will check whether the input text contains something to replace, and replace if applicable.
Two things to note the original goal. Firstly, there is a nested loop to solve the scenario where a certain keyword exists several times, so several replacements are required. Secondly, I also had to deal with variable-length wildcards and set the replacement flag in the table under discussion. These two things plus the other are probably the reason that you will find a lot of weird stuff flying around.
CREATE FUNCTION [JACKINABOX](@TextToUpdate varchar(30), @FilterId int) RETURNS varchar(30) AS BEGIN DECLARE @Keyword varchar(30) DECLARE LonelyCursor CURSOR FOR SELECT Keyword FROM ReplacementInformation WHERE Id = @FilterId OPEN LonelyCursor ; FETCH NEXT FROM LonelyCursor INTO @Keyword WHILE @@FETCH_STATUS = 0 -- While there still remains keywords to process. BEGIN WHILE 1 = 1 -- Not sure, but I think this nested loop can be unlooped if [FETCH NEXT] was cut & pasted to replace [BREAK]. BEGIN IF(CHARINDEX(@Keyword, @TextToUpdate) = 0) BREAK -- If cannot find current keyword anymore, move on to next keyword. ELSE -- Otherwise, update text then check again for same keyword. SET @TextToUpdate = REPLACE(@TextToUpdate, @Keyword, CONCAT('Replaced_', @Keyword)) END FETCH NEXT FROM LonelyCursor INTO @Keyword END CLOSE LonelyCursor ; DEALLOCATE LonelyCursor RETURN @TextToUpdate END