Solved

how to update a table recursively sql server 2005?

Posted on 2009-07-07
4
441 Views
Last Modified: 2012-05-07
Hello Experts,


There is an Employee table with (Empid, empname, ManagerID, salary)

i need toi update salary for all employees of s perticular manager? I am trying with recursive CTE syntax. But no luck.

Could you please help me on this?

Thanks,
itsvtk



0
Comment
Question by:Thandava Vallepalli
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 24799907
why cant you get the ids of all the employee reporting to the manager

;WITH CTE_EmpList ( ManagerID )
AS (
-- anchor members
SELECT e.ManagerID
FROM Employee e
WHERE ManagerID = @managerID

UNION ALL
-- recursive members
SELECT e.ManagerID
FROM Employee e
INNER JOIN CTE_EmpList d ON e.ManagerID = d.EmployeeID
)
0
 
LVL 15

Expert Comment

by:rob_farley
ID: 24799996
Do you need recursion? What about:

UPDATE Employee SET ...
WHERE ManagerID = @MgrID
0
 
LVL 15

Accepted Solution

by:
rob_farley earned 250 total points
ID: 24800012
If you need the whole Organisation Structure under that manager, then try:

--Make sure the previous query has ended in a semi-colon.

WITH EmployeesToUpdate AS (
--Start with the Manager themself
SELECT @MgrID AS EmployeeID
UNION ALL
--And now pull in the people that report to them (recursively)
SELECT e.EmployeeID
FROM Employee e JOIN EmployeesToUpdate m
  ON e.ManagerID = m.EmployeeID
)
UPDATE e SET ....
FROM Employee e JOIN EmployeesToUpdate u
  ON e.EmployeeID = u.EmployeeID
;
 
0
 
LVL 41

Expert Comment

by:Sharath
ID: 24800201
Is it possible to explain with some sample data and how do you want to update?
0

Featured Post

Edgartown IT Case Study

Learn about Edgartown's quest to ensure the safety and security of the entire town's employee and citizen data. Read the case study!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question