SQL Server 数据Update的步骤

时间:2024-02-21 08:32:31

 

Update的语法:

Update dbo.Table
  
Set column = Value (or expression)
      ……
  
[From data sources]
  
[Where conditions]

这里不讨论简单的“列-标量”对的Update方法,Update的强大在于它可以可以结合SQL Select的全部功能构成非常复杂的数据源,下面讨论使用Select的构成数据源的步骤:

1.检查可用数据,使用查询设计器构成Select语句,得到基本数据源 

 

 

SELECT     Employee.EmployeeID, Employee.Name, Employee.Salary, Employee.PerformRating, Employee.DateHire, Employee.DatePosition, 
                      Department.RaiseFactor, Department.Name 
AS Department
FROM         Employee INNER JOIN
                      Department 
ON Employee.DepartmentID = Department.departmentID

 

2.测试公式,得到更新数据源 

SELECT     Employee.EmployeeID,Employee.Salary * (1 + (2 + ((DATEDIFF(yy, Employee.DateHire, GETDATE()) * .1 + DATEDIFF(mm, Employee.DatePosition, GETDATE()) * .02
                      
+ CASE WHEN Employee.PerformRating >= 2 THEN PerformRating ELSE 0 END * .5* Department.RaiseFactor) / 100As NewSalary
FROM         Employee INNER JOIN
                      Department 
ON Employee.DepartmentID = Department.departmentID

 

 

3.进行更新,将Select的From子句移到Update层,无需修改Select子句

    UPDATE    Employee
SET              Salary = Employee.Salary * (1 + (2 + ((DATEDIFF(yy, Employee.DateHire, GETDATE()) * .1 + DATEDIFF(mm, Employee.DatePosition, GETDATE()) * .02
                      
+ CASE WHEN Employee.PerformRating >= 2 THEN PerformRating ELSE 0 END * .5* Department.RaiseFactor) / 100)
FROM         Employee INNER JOIN
                      Department 
ON Employee.DepartmentID = Department.departmentID