I have Organizations table:
Id Name ParentId
------------------
1 Org1 5
2 Org2 5
3 Org3 4
4 Depart2 6
5 Depart1 6
6 Company null
What I would like to achieve is query which returns table with belonging of each organization to higher order organization units up in hierarchy tree:
Id BelongsToOrgId
1 1 Org1 is part of Org1
1 5 Org1 is part of Depart1
1 6 Org1 is part of Company
2 2 Org2 is part of Org2
2 5 Org2 is part of Depart1
2 6 Org2 is part of Company
3 3 Org3 is part of Org3
3 4 Org3 is part of Depart2
3 6 Org3 is part of Company
4 4 Depart2 is part of Depart2
4 6 Depart2 is part of Company
5 5 Depart1 is part of Depart1
5 6 Depart1 is part of Company
6 6 Company is part of Company
Best Regards, Piotr