使用Sqlserver中的Select Query进行更新

时间:2011-02-08 10:04:30

标签: sql-server-2005

我有一名员工

DeptID  Name
1       manu
2       kiran
3       anu
4       manoj
0       peter
0       Kumar
0       mike

还有一个名为Department

的表
DeptID  DepName
1        CS
2        IS
3        EE 
0        RR

查询

update employee
set DeptID = 7 where  exists(   
SELECT * FROM   Department WHERE (DeptID = 0))

通过Exceuting this Query,结果集将employee表中的所有DepID更改为7

我想只将DeptID更改为7,其中DeptID为“0”。 这是我试图告诉你的一个问题。在我真正的数据库中我遇到了这样的问题

请帮我解决问题  感谢

2 个答案:

答案 0 :(得分:0)

update employee
set DeptID = 7 where  exists(   
SELECT * FROM   Department WHERE (DeptID = 0))
where DeptID = 0

您必须在更新语句中再添加一个条件。

如果您只是将DeptID = 0到7的所有员工都更新,那么您也不需要使用子查询。以下查询将执行 -

update employee
set DeptID = 7
where DeptID = 0

答案 1 :(得分:0)

这会将员工中的所有DeptID设置为7,其中DeptID为0

update Employee
set DeptID = 7
where DeptID = 0

Employee.DeptID可能是来自Department.DeptID的外键,因此您必须先确保Department存在DeptID = 7

在您的示例数据中,您有一个名为“RR”的部门。如果那是您想要使用但DeptID = 7的那个,你可以这样做。

-- Add Department with DeptID = 7
insert into Department(DeptID, DepName)
select 7, DepName
from Department
where DeptID = 0

-- Change DeptID to 7 for Employee's with DeptID = 0
update Employee
set DeptID = 7
where DeptID = 0

-- Delete Department
delete Department
where DeptID = 0

编辑1 这也可以,但我没有看到使用它的意义。您的更新语句已修改为仅使用DeptID=0

更新员工
update employee
set DeptID = 7
where
  exists(select *
         from Department
         where (DeptID = 0)) and
  DeptID = 0
相关问题