tags:

views:

55

answers:

1

I need to update the managerid field with the related employeeid.

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
+3  A: 

You can join on the Employee table to find a manager's id:

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

Be aware that storing both the manager's name and the manager's id in an employee row violates 3rd Normal Form.

Andomar
Thanks Andomar! I was trying to update employee instead of update emp. Thank you very much!
cf_PhillipSenn
I will remove ManagerName after I get ManagerID populated.
cf_PhillipSenn