• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 648
  • Last Modified:

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?
0
enrique_aeo
Asked:
enrique_aeo
  • 5
  • 3
  • 3
5 Solutions
 
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.
0
 
enrique_aeoAuthor Commented:
i need the code in transact sql please
0
 
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?
0
Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

 
enrique_aeoAuthor Commented:
you mean that it is very difficult to do with temporary tables?
0
 
enrique_aeoAuthor Commented:
I ATTached the data
hrEMPLOYEES.txt
0
 
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
0
 
enrique_aeoAuthor Commented:
I ATTached the data
data.xlsx
0
 
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
0
 
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

0
 
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
0
 
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
0

Featured Post

Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

  • 5
  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now