Is it possible to do bulk replace without while loop or what is the best way
Table-1
+-------+--------+
| name | value |
+-------+--------+
| @1@ | one |
| @2@ | two |
| @3@ | three |
+-------+--------+
Table-2 (updated: there is more than one different tokens in table2)
+-----------------------+
| col1 |
+-----------------------+
| string @1@ string @2@ |
| string @2@ string @1@ |
| string @3@ string @2@ |
+-----------------------+
I like to replace all token from Table-2 with Table-1's value column respectively.
Expected Result
+-------------------------+
| col1 |
+-------------------------+
| string one string two |
| string two string one |
| string three string two |
+-------------------------+
Current solution with While loop
declare @table1 table(name nvarchar(50),value nvarchar(50))
insert into @table1 values('@1@','one'),('@2@','two'),('@1@','three')
declare @table2 table(col1 nvarchar(50))
insert into @table2 values('string @1@ string @2@'),('string @2@ string @1@'),('string @3@ string @2@')
WHILE EXISTS (SELECT 1 FROM @table2 t2 INNER JOIN @table1 t1 ON CHARINDEX(t1.name,[col1])>0)
BEGIN
UPDATE @table2
SET col1=REPLACE(col1,name,value)
FROM @table1
WHERE CHARINDEX(name,[col1])>0
END
select * from @table2
Thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…