0

我需要用相关的employeeid 更新managerid 字段。

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
4

1 回答 1

5

您可以加入 Employee 表以查找经理的 ID:

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

请注意,在员工行中同时存储经理的姓名和经理的 ID 违反了第 3 范式

于 2009-05-20T12:33:55.147 回答