2009-05-20 41 views
0

我需要與相關僱員更新經理ID字段。正火數據

CREATE TABLE Employee(
EmployeeID Int Primary Key Identity, 
Name Varchar(50), 
ManagerID INT default 0, 
ManagerName Varchar(50) default '' 
) 
INSERT INTO Employee(Name,ManagerName) VALUES('Dilbert','Boss') 
INSERT INTO Employee(Name,ManagerName) VALUES('Boss','Dogbert') 
INSERT INTO Employee(Name) VALUES('Dogbert') 
SELECT * FROM Employee 
GO 
-- This is the update stmt I need help with 
UPDATE Employee 
SET ManagerID=EmpID 
WHERE ManagerName = Name 

回答

5

您可以加入在Employee表上找到了經理的ID:

UPDATE emp 
SET ManagerID = boss.EmployeeID 
FROM Employee emp 
INNER JOIN Employee boss 
    ON boss.Name = emp.ManagerName 

要知道,僱員行中存儲兩個經理的名字和經理的ID違反了3rd Normal Form

+0

謝謝Andomar!我試圖更新員工而不是更新emp。非常感謝你! – 2009-05-20 12:39:49