查找并替换n个单词

liwlm1x9  于 2022-10-22  发布在  其他
关注(0)|答案(1)|浏览(224)

我有以下结构,其中某些单词需要替换

declare @Words table(Find varchar(50),Replace varchar(50))

Insert Into @Words
Values('aeroplane','airplane'),
      ('centre','center'),
      ('holiday','vacation')

当前必须循环浏览此表,并使用REPLACE替换每一行
有人会建议一种有效的方法来实现这一点,而不是遍历@words表吗?

mrfwxfqh

mrfwxfqh1#

作为帮助您用一个查询修改数据的常规查询,您可以执行以下操作:

CREATE TABLE MyTable (ID INT, MyColumn VARCHAR(256))

INSERT INTO MyTable VALUES
(1, 'toto'),
(2, 'toto aeroplane titi'),
(3, 'le centre des holidays');

WITH
WORDS AS
(SELECT *
 FROM   (VALUES ('aeroplane','airplane'),
                ('centre','center'),
                ('holiday','vacation')) AS T (FindWord, ReplaceWord)
),
RPLC AS
(
SELECT ID, MyColumn, FindWord, ReplaceWord, 
       ROW_NUMBER() OVER(PARTITION BY ID ORDER BY FindWord)  AS N,
       COUNT(*) OVER(PARTITION BY MyColumn) AS M
FROM   MyTable AS T
       JOIN WORDS ON T.MyColumn LIKE '%' + FindWord + '%'
),
MODIF AS
(
SELECT ID, MyColumn, REPLACE(MyColumn, FindWord, ReplaceWord) AS MyNewColumn, N,
       M
FROM   RPLC 
WHERE  N = 1
UNION ALL
SELECT R.ID, M.MyColumn, REPLACE(MyNewColumn, R.FindWord, R.ReplaceWord), R.N, R.M
FROM   MODIF  AS M
       JOIN RPLC AS R ON M.ID = R.ID AND M.N +1 = R.N
)
SELECT * 
FROM   MODIF 
WHERE  M = N;

只需将最后的SELECT替换为与原始表连接的UPDATE

相关问题