规范化数据

时间:2009-05-20 12:30:45

标签: sql sql-server database-normalization

我需要使用相关的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

1 个答案:

答案 0 :(得分: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