Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 SQL CTEs

Author  Topic 

Haarish
Starting Member

30 Posts

Posted - 2009-06-13 : 02:46:27
Hi Guys,

I have a table like the one below.

ID--------EMPNAME--------MANAGERID
__________________________________
1------------A-------------NULL
2------------B--------------1
3------------C--------------4
4------------D--------------2
5------------E--------------3
6------------F--------------5

What I intend to do is to do an iteration on this table to find the manager of each employee at the highest level. In this case the Manager at the top most level for each employee would be 'A'. What is the best way of doing this? I cant quite understand the construct of CTE's. Can anyone give me a sample SQL query to get this done?

Thanks in advance,
Haarish.

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2009-06-13 : 10:22:43
Do you mean this?
--ID--------EMPNAME--------MANAGERID
--__________________________________
--1------------A-------------NULL
--2------------B--------------1
--3------------C--------------4
--4------------D--------------2
--5------------E--------------3
--6------------F--------------5
declare @sample table(id int, empname varchar(255), managerid int)
insert @sample
select 1,'A',NULL union all
select 2,'B',1 union all
select 3,'C',4 union all
select 4,'D',2 union all
select 5,'E',3 union all
select 6,'F',5

--select * from @sample

;WITH cte (managerid,id,empname)
AS
(
-- Anchor member definition
SELECT e.ManagerID, e.ID, e.empname
FROM @sample as e
WHERE ManagerID IS NULL
UNION ALL
-- Recursive member definition
SELECT e.ManagerID, e.ID, e.empname
FROM @sample as e
INNER JOIN cte AS d
ON e.ManagerID = d.ID
)

select id,empname,managerid from cte

I have taken an example from BOL and adapted it to your data.


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-06-14 : 02:11:59
http://msdn.microsoft.com/en-us/library/ms186243.aspx
Go to Top of Page
   

- Advertisement -