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

时间:2015-01-14 19:00:01

标签: sql-server tsql

我正在使用SQL Server 2014。

我有这张桌子:说T1。只有2列。

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

另一张桌子,比如T2:

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

我想更新T1.Desc以摆脱T2上的相关字词('"""""医生")

这是我的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",但"医生"还在那里。

你能否为我提供正确的SQL来实现这个目标?

2 个答案:

答案 0 :(得分:1)

您需要使用cursorwhile loop

来执行此操作

这是使用递归cte

的另一种方法

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

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

;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

答案 1 :(得分: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