Create a new table as below:
CREATE TABLE [dbo].[Employee](
[EmployeeID] [int] NOT NULL,
[EmpName] [varchar](100) NULL,
[Department] [varchar](100) NULL,
[Designation] [varchar](100) NULL,
[Salary] [money] NULL,
[ManagerID] [int] NULL
) ON [PRIMARY]
Insert valuse to the table:
SELECT L3.EmpName AS LEVEL2, L2.EmpName LEVEL1, L1.EmpName LEVEL0
,CAST(ISNULL(L3.EmployeeID,'') AS VARCHAR(5))+'/' + CAST(ISNULL(L2.EmployeeID,'') AS VARCHAR(5))+'/' + CAST(ISNULL(L1.EmployeeID,'') AS VARCHAR(5)) AS LEVELPATH
,CAST(ISNULL(L3.EmpName,'') AS VARCHAR(5))+'/' + CAST(ISNULL(L2.EmpName,'') AS VARCHAR(5))+'/' + CAST(ISNULL(L1.EmpName,'') AS VARCHAR(5)) AS EMPLOYETREE
FROM Employee L1
LEFT JOIN Employee L2 ON L1.ManagerID = L2.EmployeeID
LEFT JOIN Employee L3 ON L2.ManagerID = L3.EmployeeID
LEFT JOIN Employee L4 ON L3.ManagerID = L4.EmployeeID
LEFT JOIN Employee L5 ON L4.ManagerID = L5.EmployeeID
CREATE TABLE [dbo].[Employee](
[EmployeeID] [int] NOT NULL,
[EmpName] [varchar](100) NULL,
[Department] [varchar](100) NULL,
[Designation] [varchar](100) NULL,
[Salary] [money] NULL,
[ManagerID] [int] NULL
) ON [PRIMARY]
Insert valuse to the table:
SELECT L3.EmpName AS LEVEL2, L2.EmpName LEVEL1, L1.EmpName LEVEL0
,CAST(ISNULL(L3.EmployeeID,'') AS VARCHAR(5))+'/' + CAST(ISNULL(L2.EmployeeID,'') AS VARCHAR(5))+'/' + CAST(ISNULL(L1.EmployeeID,'') AS VARCHAR(5)) AS LEVELPATH
,CAST(ISNULL(L3.EmpName,'') AS VARCHAR(5))+'/' + CAST(ISNULL(L2.EmpName,'') AS VARCHAR(5))+'/' + CAST(ISNULL(L1.EmpName,'') AS VARCHAR(5)) AS EMPLOYETREE
FROM Employee L1
LEFT JOIN Employee L2 ON L1.ManagerID = L2.EmployeeID
LEFT JOIN Employee L3 ON L2.ManagerID = L3.EmployeeID
LEFT JOIN Employee L4 ON L3.ManagerID = L4.EmployeeID
LEFT JOIN Employee L5 ON L4.ManagerID = L5.EmployeeID
No comments:
Post a Comment