I have a hierarchy like following Group Company Department Cost Centre Which are being stored in database like following table structure.
Table Name : OrgHierarchy Columns : Id, ParentId, Level, Type
In My Employee View I have employee Cost Centre, Department, Company and Group present.
I need help in writing better performing query to find employee for a particular node in the hierarchy (it can be Group/Company/Department/Cost Centre)
Select * from vw_Employee emp
Where emp.CostCentreId = @NodeId
OR emp.DepartmentId=@NodeId
OR emp.CompanyId=@NodeId
OR emp.GroupId= @NodeId
Here the number of “OR” statement making the query very slow.
Is there any better approach to handle the efficiently or any other approach?
Using OR
in condition makes indexis be skipped. Replace it with UNION
:
Select *
from vw_Employee emp
Where emp.CostCentreId = @NodeId
UNION
Select *
from vw_Employee emp
Where emp.DepartmentId=@NodeId
UNION
Select *
from vw_Employee emp
Where emp.CompanyId=@NodeId
UNION
Select *
from vw_Employee emp
Where emp.GroupId= @NodeId
Here is a good question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.