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?
enrique_aeoAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sameer_goyalCommented:
prior to introduction of CTE in 2005, to do the above, temporary tables were the only way to do. But CTEs are perfect and low on performance cost when solving the cases like above.

You can always do it using a temp table and self joins.
enrique_aeoAuthor Commented:
i need the code in transact sql please
lwadwellCommented:
This is a recursive CTE ... i.e. it joins to itself in a loop until no more rows are generated or max recursion limit is reached.
Turning it into procedure code would be complex and difficult.  Why do you want to?
IT Pros Agree: AI and Machine Learning Key

We’d all like to think our company’s data is well protected, but when you ask IT professionals they admit the data probably is not as safe as it could be.

enrique_aeoAuthor Commented:
you mean that it is very difficult to do with temporary tables?
enrique_aeoAuthor Commented:
I ATTached the data
hrEMPLOYEES.txt
sameer_goyalCommented:
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
enrique_aeoAuthor Commented:
I ATTached the data
data.xlsx
enrique_aeoAuthor Commented:
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
lwadwellCommented:
As I tried to explain ... a recursive CTE uses a loop to walk all levels ... it cannot be done outside of a CTE without a loop.  To use temp table something like below is required:

-- Create testing data
IF OBJECT_ID('tempdb..#tmp_data') IS NOT NULL
	DROP TABLE #tmp_data;
CREATE TABLE #tmp_data (
	empId int, 
  mgrId int, 
  firstname nchar(10), 
  lastname nchar(10)
);
insert into #tmp_data values
(12,9,'Lisa','Simpson'),
(11,9,'Maggie','Simpson'),
(10,9,'Bart','Simpson'),
(9,8,'Homer','Simpson'),
(8,3,'Marge','Simpson'),
(7,3,'Waylon','Smithers'),
(6,3,'Carl','Carlson'),
(5,3,'Lenny','Leonard'),
(4,3,'The','Duffman'),
(3,2,'Montgomery','Burns'),
(2,1,'Matt','Groening'),
(1,null,'Rupert','Murdoch');
-- END Create testing data

-- Start of example logic
IF OBJECT_ID('tempdb..#tmp_cte') IS NOT NULL
	DROP TABLE #tmp_cte;
CREATE TABLE #tmp_cte (
	empId int, 
  mgrId int, 
  firstname nchar(10), 
  lastname nchar(10),
  lvl   int
);

declare @i int
set @i = 0
insert into #tmp_cte (empId, mgrId, firstname, lastname, lvl)
select empId, mgrId, firstname, lastname, @i as lvl
from #tmp_data
where empId = 9;

while @@rowcount > 0 and @i < 100 
begin 
  set @i = @i + 1
  insert into #tmp_cte (empId, mgrId, firstname, lastname, lvl)
  select td.empId, td.mgrId, td.firstname, td.lastname, @i as lvl
  from #tmp_cte cte
  inner join #tmp_data td on cte.mgrId = td.empId
  where cte.lvl = @i - 1;
end

select *
from #tmp_cte

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sameer_goyalCommented:
Hi,

You have to use HR.Employees in the query after Union All clause.

you are trying to use the #tmpEmp table which is actually getting populated at that time.

Try this and let me know

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
.[Employees] A,
.[Employees] B
where A.empId = 5 -- You can change this
And (B.MgrId = A.empid or B.MgrId = null)


select * from #tmpEmp
lwadwellCommented:
apologies ... I built my example was walking from the employee UP through the hierarchy to the top.   On closer inspection, your original was walking down from manager down to employee, then their employees, their employees employees etc.
That would be a change to the join in the while loop from:
    inner join #tmp_data td on cte.mgrId = td.empId
to:
    inner join #tmp_data td on td.mgrId = cte.empId
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.