Hi,
I have a table EmployeeHierarchy
with EmployeeID
and ManagerID
. I need to write a recursive query to get the hierarchy of employees. Any suggestions?
Home / DeveloperSection / Forums / Help with Writing a Recursive Query in SQL Server
Hi,
I have a table EmployeeHierarchy
with EmployeeID
and ManagerID
. I need to write a recursive query to get the hierarchy of employees. Any suggestions?
Ravi Vishwakarma
16-Jul-2024Recursive queries in SQL Server are typically written using Common Table Expressions (CTEs). These are particularly useful for hierarchical data, such as organizational charts, family trees, or any dataset that has a parent-child relationship.
Here's a basic example to illustrate how to write a recursive query using a CTE in SQL Server. We'll use a hypothetical organizational structure as an example.
Example: Organizational Hierarchy
Assume we have a table named
Employees
with the following structure:In this table:
EmployeeID
is the unique identifier for each employee.EmployeeName
is the name of the employee.ManagerID
is theEmployeeID
of the employee's manager. The top-level manager (Alice) has aNULL
ManagerID
.Recursive Query
Retrieve the entire hierarchy starting from the top-level manager.
Here's how you can write a recursive CTE to achieve this:
Explanation:
Anchor Member:
SELECT
statement in the CTE defines the anchor member, which retrieves the top-level manager(s) (those withNULL
ManagerID
).Recursive Member:
SELECT
statement in the CTE joins theEmployees
table with theEmployeeCTE
onManagerID
andEmployeeID
, effectively retrieving the employees managed by each employee in theEmployeeCTE
.Level
is incremented by 1 to indicate the hierarchy level.Final SELECT:
SELECT
statement retrieves the data from the CTE, and theORDER BY
clause is used to sort the results by hierarchy level andEmployeeID
.This recursive query will produce the hierarchical structure of the organization, starting from the top-level manager down to the lowest level.
Read more
Define the PIVOT Table with examples in the SQL server.
Explain the SQL triggers and their uses
Explain the SQL Server backups and their types