使用另一个表中的数据进行更新

以下示例为任何员工填写 PhoneNumber,该员工也是 Customer,目前没有在 Employees 表中设置的电话号码。

(这些示例使用示例数据库中的 EmployeesCustomers 表。)

标准 SQL

使用相关子查询更新:

UPDATE 
    Employees
SET PhoneNumber =
    (SELECT 
         c.PhoneNumber
     FROM 
         Customers c
     WHERE 
         c.FName = Employees.FName 
         AND c.LName = Employees.LName)
WHERE Employees.PhoneNumber IS NULL

SQL:2003

使用 MERGE 更新:

MERGE INTO 
    Employees e
USING 
    Customers c 
ON 
    e.FName = c.Fname 
    AND e.LName = c.LName
    AND e.PhoneNumber IS NULL
WHEN MATCHED THEN
   UPDATE 
      SET PhoneNumber = c.PhoneNumber

SQL Server

使用 INNER JOIN 更新:

UPDATE 
    Employees
SET 
    PhoneNumber = c.PhoneNumber
FROM 
    Employees e
INNER JOIN Customers c
        ON e.FName = c.FName 
        AND e.LName = c.LName
WHERE 
    PhoneNumber IS NULL