In my database (SQL Server) I have a table for employee information. Each employee has a manager. There is a hierarchical structure of employees in the table. Below is few demo data from this table
EmpId | Name | Managerid
----- | ------- | ---------
1 | John | 0
2 | Thomas | 1
3 | William | 1
4 | Richard | 3
5 | Mary | 0
6 | Anne | 4
7 | Matthew | 5
8 | Samuel | 7
9 | Sarah | 8
10 | Walter | 5
11 | Ellen | 3
12 | Amy | 0
13 | Rachel | 12
14 | David | 4
15 | Lucy | 3
My requirement is to find out the top most manager of each employee. So the result should look like
EmpId | Name | ManagerName
----- | ------- | ---------
1 | John | -
2 | Thomas | John
3 | William | John
4 | Richard | John
5 | Mary | -
6 | Anne | John
7 | Matthew | Mary
8 | Samuel | Mary
9 | Sarah | Mary
10 | Walter | Mary
11 | Ellen | John
12 | Amy | -
13 | Rachel | Amy
14 | David | John
15 | Lucy | John
How can I get this result.