I am trying to understand the concepts of using CTE in my SQL code. I have gone through a number of online posts explaining the concept but I cannot grasp how it iterates to pre
So you want to understand a recursive CTE.
It's simple really.
First there's the seed query which gets the original records.
SELECT EmployeeID, ContactID, LoginID, ManagerID, Title, BirthDate
FROM HumanResources.Employee
WHERE ManagerID IS NULL
In your case it's the employees without a manager.
Which would be the boss(es)
To demonstrate with a simplified example:
EmployeeID LoginID ManagerID Title
---------- ------- --------- ------------
101 boss NULL The Boss
The second query looks for employees that have the previous record as a manager.
SELECT e.EmployeeID, e.ContactID, e.LoginID, e.ManagerID, e.Title, e.BirthDate
FROM HumanResources.Employee e
INNER JOIN Emp_CTE ecte ON ecte.EmployeeID = e.ManagerID
Since it's a recursive CTE, the CTE uses itself in the second query.
You could see it as a loop, where it uses the previous records to get the next.
For the first iteration of that recursive loop you could get something like this:
EmployeeID LoginID ManagerID Title
---------- ------- --------- ------------
102 head1 101 Top Manager 1
103 head2 101 Top Manager 2
For the second iteration it would use the records from that first iteration to find the next.
EmployeeID LoginID ManagerID Title
---------- ------- --------- ------------
104 bob 102 Department Manager 1
105 hilda 102 Department Manager 2
108 john 103 Department Manager 4
109 jane 103 Department Manager 5
For the 3th iteration it would use the records from the 2nd iteration.
...
And this continues till there are no more employees to join on the ManagerID
Then after all the looping, the CTE will return all the records that were found through all those iterations.