Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

Sql Server: CTE Recursive Query to Get Employee Manager Hierarchy with Level

$
0
0

Introduction : In this article I have explained How to get parent child hierarchical relationship with levels using CTE (Common Table Expression) recursive query in sql.

In previous articles i explained How to Drop or truncate parent table by dropping all foreign key constraints and CTE to remove duplicate records from table and Autogenerate auto incremented unique alphanumeric id or number in sql server and Multiple queries to get all dates between two dates and Without primary key column update first or last n records in table

Description : While working with database we often store parent and child id in same table. For example Category and sub category Id, Employee and his manager id etc. Here in this article I am taking an example where employees and their manager are stored in same table. And suppose it is required to get employee and his manager and hierarchical level of employee in organization. CTE is very useful in such case because of its recursive capability.

Implementation : Let’s understand how it works.

Let’s create table using following script CREATE TABLE tbEmployee ( EmployeeId INT PRIMARY KEY , EmployeeName VARCHAR (50), ManagerId INT ) Enter some dummy data in table using following insert query:

INSERT tbEmployee

VALUES

( 25 , 'Salman' ,NULL),

( 26 , 'Ranbeer' , 25 ),

( 27 , 'Hrithik' , 25 ),

( 28 , 'Aamir' , 27 ),

( 29 , 'Shahid' , 28 ),

( 30 , 'Sidharth' , NULL),

( 31 , 'Varun' , 30 ),

( 32 , 'Kabeer' , 30 ),

( 33 , 'Raj' , 29 );

Show table data SELECT * FROM tbEmployee Result: EmployeeId EmployeeName ManagerId 25 Salman NULL 26 Ranbeer 25 27 Hrithik 25 28 Aamir 27 29 Shahid 28 30 Sidharth NULL 31

Viewing all articles
Browse latest Browse all 3160

Trending Articles