根据另一个表中是否存在值进行更新

use*_*480 4 sql sql-server syntax case sql-update

我有两张桌子

表A

Number
111       
222       
333       
444       
Run Code Online (Sandbox Code Playgroud)

表B

Number    Another
111       AAA
222       BBB
666       CCC
777       DDD
Run Code Online (Sandbox Code Playgroud)

我想做的是应用一个UPDATE语句,条件是表A中是否存在表B中的“ Number”值。因此,该表最终看起来像这样。

Number    Another
111       ZZZ
222       ZZZ
666       CCC
777       DDD
Run Code Online (Sandbox Code Playgroud)

我知道我需要使用UPDATE查询和可能的某种JOIN,但是我不确定语法。

任何帮助,不胜感激。

Man*_*oor 6

您可以直接使用 SELECT FROM table1 并更新到 table2 :

UPDATE table2 SET Another = 'ZZZ' 
FROM table1 t1 WHERE t1.Number = table2.Number
Run Code Online (Sandbox Code Playgroud)


Gur*_*ngh 5

是。您需要使用这样的联接进行更新:

update t2
set t2.Another = 'ZZZ'
from table1 t1
join table2 t2 on t1.Number = t2.Number
Run Code Online (Sandbox Code Playgroud)


Ull*_*las 5

您也可以使用exists

询问

update t1
set t1.[Another] = 'ZZZ'
from [TableB] t1
where exists(
    select 1 from [TableA] t2
    where t1.[Number] = t2.[Number]
);
Run Code Online (Sandbox Code Playgroud)