I'm trying to get repeated employees (Managers - director - CEO to have full hierarchy) with DepartmentCode
similar to Lvl
column from Recursive query result.
Found couple of existing Q&A but those are not seem to fit with my case. The aim is to have full hierarchy until the root node (CEO) when the result data filtered with any DepartmentCode
. When i tried with following recursive CTE, it looks perfect with Lvl
column i.e. when data filtered any ID of Lvl
column it gets Employees, Mangers, Directors and CEO (the full hierachy chain).
I'm wondering if the same can be applied for DepartmentCode
column using Recursive CTE or using some other approach. Any advise would be appreciable!
Query that i tried, result is here.. (I'm fine with the duplicate values that appears in result)
WITH CTE AS
(
SELECT E.EmployeeID, E.EmpName, E.Title, DepartmentCode, ' ' DepartTest, E.ManagerID, 1 as Lvl
FROM MyEmployees AS E
UNION ALL
SELECT E.EmployeeID, E.EmpName, E.Title, E.DepartmentCode, E.DepartmentCode, E.ManagerID, Lvl + 1
FROM MyEmployees AS E
JOIN CTE ON E.EmployeeID = CTE.ManagerID
--E.ManagerID = CTE.EmployeeID
)
SELECT * FROM CTE
Order by Lvl
go
Sample Data script:
CREATE TABLE dbo.MyEmployees
(
EmployeeID smallint NOT NULL,
EmpName nvarchar(30) NOT NULL,
Title nvarchar(50) NOT NULL,
DepartmentCode varchar(3),
ManagerID int NULL,
CONSTRAINT PK_EmployeeID PRIMARY KEY CLUSTERED (EmployeeID ASC)
);
-- Populate the table with values.
INSERT INTO dbo.MyEmployees
(EmployeeID, EmpName, Title, DepartmentCode, ManagerID)
VALUES
(1, N'Ken', N'Chief Executive Officer', 'SMG', NULL)
,(201, N'Brian', N'Director', 'OPD',1)
,(301, N'Stephen', N'IT Manager', 'ICT',201)
,(302, N'Michael', N'IT Position1','ICT',301)
,(303, N'Linda', N'IT Position2','ICT', 301)
,(401, N'Syed', N'Procurement Position1','PRO',201)
,(402, N'Abbas', N'Procurement Position1','PRO',401)
,(403, N'Lynn', N'Procurement Position2','PRO',401)
GO