Hi @rajani desai
I noticed that you are using FROM [dbo].[Employeetable ] e, [dbo].[employeetable] m
,which means [dbo].[Employeetable ]
cross join [dbo].[employeetable]
,and it will return the Cartesian product.
Try this query:
;WITH EmployeeCTE AS
(
SELECT employeexrefcode, ManagerEmployeeNumber as topmanager
FROM [dbo].[employeetable]
UNION ALL
SELECT e.employeexrefcode, mgr.topmanager
FROM [dbo].[employeetable] e JOIN EmployeeCTE mgr ON e.ManagerEmployeeNumber = mgr.employeexrefcode
)
SELECT *
FROM EmployeeCTE
ORDER BY topmanager
In addition, you can also optimize query speed by adding appropriate indexes. In this sitution,you could add indexes on employeexrefcode and ManagerEmployeeNumber columns.
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.