Link to home
Start Free TrialLog in
Avatar of enrique_aeo
enrique_aeo

asked on

sql server 20212 CTE or temporary tables

Hi experts
i have this query
WITH EmpOrg_CTE AS
(SELECT empid, mgrid, lastname, firstname --anchor query
      FROM HR.Employees
WHERE empid = 5 -- starting "top" of tree. Change this to show other root employees

UNION ALL
SELECT child.empid, child.mgrid, child.lastname, child.firstname -- recursive member which refers back to CTE
      FROM EmpOrg_CTE AS parent
      JOIN HR.Employees AS child
      ON child.mgrid=parent.empid
)
SELECT empid, mgrid, lastname, firstname
FROM EmpOrg_CTE;

there is another way to do this without using CTE?
SOLUTION
Avatar of sameer_goyal
sameer_goyal
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of enrique_aeo
enrique_aeo

ASKER

i need the code in transact sql please
SOLUTION
Avatar of Lee Wadwell
Lee Wadwell
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
you mean that it is very difficult to do with temporary tables?
I ATTached the data
hrEMPLOYEES.txt
here you go

CREATE table #tmpEmp(empId int, mgrId int, firstname nchar(10), lastname nchar(10))

insert into #tmpEmp
SELECT empid, mgrid, firstName, lastName
      FROM Emp
WHERE empid = 5

union all

select B.empId, B.mgrId, B.firstName, B.lastName
from Emp A, Emp B
where A.empId = 5 -- You can change this
And (B.MgrId = A.empid or B.MgrId = null)


select * from #tmpEmp


not at all difficult to do with temp table
I ATTached the data
data.xlsx
the query is not working
CREATE table #tmpEmp(empId int, mgrId int, firstname nchar(10), lastname nchar(10))

insert into #tmpEmp
SELECT empid, mgrid, firstName, lastName
      FROM
.[Employees]
WHERE empid = 5

union all

select B.empId, B.mgrId, B.firstName, B.lastName
from #tmpEmp A, #tmpEmp B
where A.empId = 5 -- You can change this
And (B.MgrId = A.empid or B.MgrId = null)


select * from #tmpEmp
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial