使用另一个表中的某个字段ID更新id

时间:2013-08-21 07:02:04

标签: sql sql-server-2008-r2

如何将属于departmentID代码department的所有员工500更新为部门代码503

** tHREmployee

> EmployeeId #.......Employeee.........DepartmentID
...101...............Ajith.............101
...102...............Arathy ...........Null
...103...............Arurna............102
...104...............Ambily............101
...105...............Anjaly............Null
...106...............Babitha...........103

** tHRDepartment

 DepartmentID #.............Code
 101........................500
 102........................501
 103........................502
 105........................503
 ..

3 个答案:

答案 0 :(得分:1)

DECLARE @CodeFrom AS INT
DECLARE @CodeTo AS INT

SET    @CodeFrom = 500 
SET    @CodeTo= 503

UPDATE tHREmployee
SET    DepartmentID = (
                          SELECT DepartmentID 
                          FROM   tHRDepartment 
                          WHERE  Code = @CodeTo
                      )
FROM   tHREmployee E
       JOIN tHRDepartment D
       ON E.DepartmentID  = D.DepartmentID 
WHERE  D.Code = @CodeFrom

答案 1 :(得分:0)

这个怎么样:

 Declare @NewDepID int
 Select   @NewDepID = DepartmentID from Departments Where DepartmentCode = 503

 update tHREmployee 
 Set DepartmentID = @NewDepID
 Where DepartmentID in (Select DepartmentID from Departments Where DepartmentCode = 500)

答案 2 :(得分:0)

更新tHREmployee SET DepartmentID = 105 WHERE DepartmentID = 101;