In one table, I have long strings which contain a series of tokens that need to be replaced from values in a number of columns in a separate customer table. There are around 30 tokens but below is a representation of it. So for example, the FName value in Table2 needs to replace the [fname] token in the string in Table1 and so on.
I can do it as below with a series of nested REPLACE statements, but it's ugly and unruly given the number of tokens that need to be replaced. Any suggestions would be much appreciated?
Notes: I'm doing this in T-SQL. And the token name doesn't always match the column name 100%.
CREATE TABLE #Table1 (StringtoReplace NVARCHAR(200))
CREATE TABLE #Table2 (Greeting NVARCHAR(30), FName NVARCHAR(30), LName NVARCHAR(30))
INSERT INTO #Table1 VALUES ('[greeting] [fname] [lname] Here is the message')
INSERT INTO #Table2
VALUES ('Hello','John','Smith'),
('Hi','Fred','Jones'),
('Howdy','Sue','Brown')
SELECT REPLACE(REPLACE(REPLACE(t1.StringToReplace,'[greeting]',t2.Greeting),'[fname]',t2.fname),'[lname]',t2.lname) AS UpdatedString
FROM #Table1 t1
CROSS APPLY #Table2 t2
Here's the required output.
UpdatedString
-------------------------------------------
Hello John Smith Here is the message
Hi Fred Jones Here is the message
Howdy Sue Brown Here is the message