How can I replace all key fields in a string with replacement values from a table in T-SQL?

后端 未结 3 1067
情话喂你
情话喂你 2021-01-14 06:40

I have a table like:

 TemplateBody
 ---------------------------------------------------------------------
 1.This is To inform #FirstName# about the issues r         


        
3条回答
  •  花落未央
    2021-01-14 07:05

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

提交回复
热议问题