I am running a recursive query to build a hierarchy path for parent-child relationship. Problem is the query runs too slow. It takes 10hours and still not finish. My table EMPLOYEE has 40K rows. I am using SQL Server
Original Table
Employee | Manager |
---|---|
Luna | Jack |
Japan | Jack |
Alice | Luna |
Alex | Luna |
Jessica | Alex |
Here is my desired table with column the path
Employee | Manager | Path |
---|---|---|
Jack | Null | Jack |
Luna | Jack | Jack - Luna |
Japan | Jack | Jack - Japan |
Alice | Luna | Jack - Luna - Alice |
Alex | Luna | Jack - Luna - Alex |
Jessica | Alex | Jack - Luna - Alex - Jessica |
My query
With emp as (
select
Manager as Employee,
cast(Null as varchar(max)) as Manger,
cast(Manager as varchar(max)) as path
from Employee e1
union all
select
e2.Employee,
cast(Manager as varchar(max)) as Manger,
cast((emp.path + '-' + e2.Employee) as varchar(max)) as path
from employee e2
join emp on e2.Manager = emp.Employee
)
select *
from emp
Any idea how to improve code efficiency?