赞
踩
在SQL Server中,更新两张相关联的表是经常需要的操作,以下是一些更新两张表的不同写法示例:
假设我们有两张表 Employees 和 SalaryUpdates,我们想要根据 SalaryUpdates 中的新工资来更新 Employees 表中的工资。
这是目前最标准的写法
UPDATE a
SET a.Salary = b.NewSalary
FROM Employees a
INNER JOIN SalaryUpdates b ON a.EmployeeID = b.EmployeeID;
UPDATE Employees
SET Salary = (SELECT NewSalary FROM SalaryUpdates WHERE SalaryUpdates.EmployeeID = Employees.EmployeeID)
WHERE EXISTS (
SELECT 1 FROM SalaryUpdates WHERE SalaryUpdates.EmployeeID = Employees.EmployeeID
);
UPDATE Employees
SET Salary = CASE
WHEN Salary < (SELECT AVG(Salary) FROM Employees) THEN Salary * 1.10
WHEN Salary > (SELECT AVG(Salary) FROM Employees) THEN Salary * 0.90
ELSE Salary
END
WHERE EXISTS (
SELECT 1 FROM SalaryUpdates WHERE SalaryUpdates.EmployeeID = Employees.EmployeeID
);
BEGIN TRANSACTION;
UPDATE Employees
SET Salary = (SELECT NewSalary FROM SalaryUpdates WHERE SalaryUpdates.EmployeeID = Employees.EmployeeID)
WHERE EXISTS (
SELECT 1 FROM SalaryUpdates WHERE SalaryUpdates.EmployeeID = Employees.EmployeeID
);
– 假设还有其他更新操作
– …
IF @@ERROR = 0
BEGIN
COMMIT TRANSACTION;
PRINT 'Updates were committed.';
END
ELSE
BEGIN
ROLLBACK TRANSACTION;
PRINT 'Updates were rolled back due to an error.';
END
UPDATE Employees
SET Salary = NewSalary
FROM Employees a, SalaryUpdates b
WHERE a.EmployeeID = b.EmployeeID
操作后,验证数据以确保更新正确无误。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。