SQL 更新问题 - 多次更新单个值

SQL update issue - Update single value multiple times

我正在使用 SQL Server 2014。

我有这个table:说T1。只有 2 列。

RecID    Desc
-----------------------------------------------
5        An apple a day keeps the doctors away.

还有一个table,说T2:

RecID_FK   Word
--------------------------
   5       apple
   5       doctors

我想更新 T1.Desc 以删除 T2 上的关联词(即 "apple" 和 "doctors")

这是我的 SQL:

UPDATE A
SET A.Desc = LTRIM(RTRIM(REPLACE(' ' + A.Desc + ' ',' ' + B.Word + ' ', ' '))) 
FROM T1 As A
INNER JOIN T2 As B ON A.RecID = B.RecID_FK

这不是很好。

它删除了 "apple",但 "doctors" 仍然存在。

能否请您提供正确的 SQL 以实现此目的?

您需要使用 cursorwhile loop

这是使用递归 cte 的另一种方法

递归cte不断更新描述中的单词,直到所有单词都被替换

所有单词被替换的最后一句用于更新table

;with cte
as
( select RecID_FK, word,
  ROW_NUMBER() over ( partition by recID_FK order by ( select null)) as rn,
  COUNT(*) over ( PARTITION by recID_FK ) as cnt
  from t2

)
,cte1
as
( select recid , LTRIM(RTRIM(REPLACE(' ' + t1.[Desc] + ' ',' ' + cte.Word + ' ', ' '))) as [Desc] , 2 as n, cnt 
  from t1
  join cte
  on t1.RecID = cte.RecID_FK
  and cte.rn =1
  union all
  select recid, LTRIM(RTRIM(REPLACE(' ' + cte1.[Desc] + ' ',' ' + cte.Word + ' ', ' '))) , n+1, cte.cnt
  from cte1 
  join cte 
  on cte1.recID = cte.RecID_FK
  and cte.rn = n
)
update t1
set [Desc] = cte1.[desc]
from t1
join cte1
on cte1.RecID = t1.RecID
and cte1.n = cte1.cnt +1

它只会更新第一个加入匹配。试试这个:

while @@ROWCOUNT > 0
    begin
        UPDATE A
        SET A.Desc = LTRIM(RTRIM(REPLACE(' ' + A.Desc + ' ',' ' + B.Word + ' ', ' '))) 
        FROM T1 As A
        INNER JOIN T2 As B ON A.RecID = B.RecID_FK
            and A.Desc like '% ' + B.Word + ' %'
    end