I have a table like:
TemplateBody
---------------------------------------------------------------------
1.This is To inform #FirstName# about the issues r
A common table expression would allow you to loop through your templates and replace all variables in that template using a variables table. If you have a lot of variables, the level of recursion might go beyond the default limit of 100 recursions. You can play with the MAXRECURSION
option according to your need.
DECLARE @Templates TABLE(Body nvarchar(max));
INSERT INTO @Templates VALUES ('This is to inform #FirstName# about the issues regarding #Location#');
DECLARE @Variables TABLE(Name nvarchar(50), Value nvarchar(max));
INSERT INTO @Variables VALUES ('#FirstName#', 'Joseph William'),
('#Location#', 'Alaska');
WITH replacing(Body, Level) AS
(
SELECT t.Body, 1 FROM @Templates t
UNION ALL
SELECT REPLACE(t.Body, v.Name, v.Value), t.Level + 1
FROM replacing t INNER JOIN @Variables v ON PATINDEX('%' + v.Name + '%', t.Body) > 0
)
SELECT TOP 1 r.Body
FROM replacing r
WHERE r.Level = (SELECT MAX(Level) FROM replacing)
OPTION (MAXRECURSION 0);