Click here to Skip to main content
15,888,293 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please help me to get employees based on manager and supervisor in SQL Server 2014.
Please find the below table.

EmpID	EmpName	       SuperviserName	   SuperviserID
111	    Employee       Superviser 	       115
115	    Superviser     Manager	           116
116	    Manager	       VP	               117
117	    VP	           CEO	               222

If i pass parameter as '115' i need output in this way:

EmpID	EmpName	       SuperviserName	   SuperviserID
111	    Employee       Superviser 	       115

If i pass parameter as '116' i need output in this way:

EmpID	EmpName	       SuperviserName	   SuperviserID
111	    Employee       Superviser 	       115
115	    Superviser     Manager	           116


If i pass parameter as '222' i need output in this way:

EmpID	EmpName	       SuperviserName	   SuperviserID
111	    Employee       Superviser 	       115
115	    Superviser     Manager	           116
116	    Manager	       VP	               117
117	    VP	           CEO	               222
Posted

1 solution

SQL
-- Declare variable for SuperViserID
DECLARE @TempSuperviserID INT; 
SET @TempSuperviserID = 222;

-- Recursive CTE
WITH AllEmployee AS 
(  
SELECT EmpID, EmpName, SuperviserName, SuperviserID
FROM Employee
WHERE SuperviserID  = @TempSuperviserID
UNION ALL
SELECT e.EmpID, e.EmpName, e.SuperviserName, e.SuperviserID
FROM Employee e
INNER JOIN AllEmployee ecte ON ecte.EmpID = e.SuperviserID
)
-- Fetching all records from CTE
SELECT * from AllEmployee     

In order to get different type output you need to change @TempSuperviserID value which is declared at the top.
 
Share this answer
 
v2
Comments
[no name] 16-Oct-15 1:39am    
I am getting this error:

Msg 205, Level 16, State 1, Line 6
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.
[no name] 16-Oct-15 2:09am    
Updated my answer. Please recheck and let me know..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900