使用加入更新
联接也可以在 UPDATE 语句中使用:
CREATE TABLE Users (
UserId int NOT NULL,
AccountId int NOT NULL,
RealName nvarchar(200) NOT NULL
)
CREATE TABLE Preferences (
UserId int NOT NULL,
SomeSetting bit NOT NULL
)
使用 Users 表中的谓词更新 Preferences 表的 SomeSetting 列,如下所示:
UPDATE p
SET p.SomeSetting = 1
FROM Users u
JOIN Preferences p ON u.UserId = p.UserId
WHERE u.AccountId = 1234
p 是语句的 FROM 子句中定义的 Preferences 的别名。只会更新 Users 表中匹配 AccountId 的行。
使用左外连接语句进行更新
Update t
SET t.Column1=100
FROM Table1 t LEFT JOIN Table12 t2
ON t2.ID=t.ID
使用内部联接和聚合函数更新表
UPDATE t1
SET t1.field1 = t2.field2Sum
FROM table1 t1
INNER JOIN (select field3, sum(field2) as field2Sum
from table2
group by field3) as t2
on t2.field3 = t1.field3