I am using following CTE to get hierarchical structure of manager and employees, i have multiple managers for one employee, in this case i do not want CTE
to repeat for that employee again and again as it is doing in my code -
getemp()
is a simple function returning employeeid, name and managerID
;With hierarchy as
(
select [Level]=1 , * from dbo.getemp() where managerid = 1
union all
select [Level]+1 , e.* from getemp() e
join hierarchy h on h.employeeid = e.managerid
)
Select * from hierarchy
After edit - Following approach working for me. Is it possible with CTE ?
SET NOCOUNT ON;
DECLARE @Rows int
SELECT [Level] = ISNULL(1,0),
employeeid = ISNULL(employeeid, 0 ),
empname = CAST(empname as varchar(10)),
managerid = ISNULL(managerid,0)
into #Temp1
from dbo.getemp() as a1
where a1.managerid = @Top1
--select * from #Temp1
SELECT @Rows=@@ROWCOUNT
DECLARE @I INT = 2;
while @Rows > 0
BEGIN
Insert into #Temp1
select @I as Level, b.employeeid, b.empname, b.managerid from #Temp1 as e
inner join (select [employeeid], [empname], [managerid] from dbo.GetEmp()) as b on b.managerid = e.employeeid
where e.Level = @I - 1
and not exists (
SELECT 1 FROM #Temp1 t
WHERE b.employeeid = t.employeeid
AND b.managerid = t.managerid);
SELECT @Rows=@@ROWCOUNT
--SELECT @Rows AS Rows
IF @Rows > 0
BEGIN
SELECT @I = @I + 1;
END
END
select distinct * from #Temp1
END