How to find Manager and Employee Level in SQL Server

In this article we will see how CTE can be used to get manager information and its employee level.

As CTE can be used in recursive and no-recursive queries. We will use recursive approach to get desired result

1. First create table with below structure

IF OBJECT_ID('tEmployees', 'U') IS NOT NULL
DROP TABLE dbo.tEmployees
GO
CREATE TABLE dbo.tEmployees
(
  EmployeeID int NOT NULL PRIMARY KEY,
  FirstName varchar(50) NOT NULL,
  LastName varchar(50) NOT NULL,
  ManagerID int NULL
)
GO

2. Insert some records into

INSERT INTO tEmployees VALUES (101, 'Ken', 'Sánchez', NULL)
INSERT INTO tEmployees VALUES (102, 'Terri', 'Duffy', 101)
INSERT INTO tEmployees VALUES (103, 'Roberto', 'Tamburello', 101)
INSERT INTO tEmployees VALUES (104, 'Rob', 'Walters', 102)
INSERT INTO tEmployees VALUES (105, 'Gail', 'Erickson', 102)
INSERT INTO tEmployees VALUES (106, 'Jossef', 'Goldberg', 103)
INSERT INTO tEmployees VALUES (107, 'Dylan', 'Miller', 103)
INSERT INTO tEmployees VALUES (108, 'Diane', 'Margheim', 105)
INSERT INTO tEmployees VALUES (109, 'Gigi', 'Matthew', 105)
INSERT INTO tEmployees VALUES (110, 'Michael', 'Raheem', 106)

3. Create Select queries using CTE

WITH
  cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
  AS
  (
    SELECT EmployeeID, FirstName, LastName, ManagerID, 1
    FROM tEmployees
    WHERE ManagerID IS NULL
    UNION ALL
    SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
      r.EmpLevel + 1
    FROM tEmployees e
      INNER JOIN cteReports r
        ON e.ManagerID = r.EmpID
  )
SELECT
  FirstName + ' ' + LastName AS FullName,
  EmpLevel,
  (SELECT FirstName + ' ' + LastName FROM tEmployees
    WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID

4. See desired result



5. References:
https://msdn.microsoft.com/en-IN/library/ms175972.aspx
https://www.simple-talk.com/sql/t-sql-programming/sql-server-cte-basics/

Comments

Popular posts from this blog

How to Add HttpModule in MVC5 Application

Map Routes using Route Class in MVC

How to convert a string with multiple comma separated values to rows in SQL Server