tsql - Update Manager Table Tree by Recursion -


i have table (see image) employees (manager manager of , on) id, parentid, salary, totalsalary. last 1 needs updated every employee had sum of descendants salary. have written script, gets total salary id , updates column in cursor, it's heavy... other ways?

declare @id int ; declare @s int ; declare curs cursor select personid dbo.employees open curs ; fetch next curs @id ; while @@fetch_status = 0      begin            xemps ( id )                   ( select   personid id                            dbo.employees                           personid = @id                        union                        select   e.personid id                            dbo.employees e                                 inner join xemps x on e.managerid = x.id                      )             select  @s = sum(salary)                dbo.employees               personid in ( select    id                                        xemps )         update  dbo.employees         set     salarysum = @s           personid = @id         fetch next curs @id     end close curs ; deallocate curs ; 

this test table of employees

the cursor not necessary, can done using recursive common table expression:

with emp (   select  employeeid, salary, managerid        dbo.employee     union     select  e.employeeid, e.salary, emp.managerid        dbo.employee e             inner join emp                 on e.managerid = emp.employeeid ) update  dbo.employee set     salarysum = coalesce(s.salary, 0) + e.salary    dbo.employee e         left join          (   select  managerid, sum(salary) [salary]                emp             group managerid         ) s             on s.managerid = e.employeeid 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -