Please consider the following tables. They describe a schools' hierarchy and the notes per student.
users
-------------------------------------------------------------
root_id    obj_id    obj_type    obj_ref_id    obj_role
-------------------------------------------------------------
1          2         student     7             learn   
1          3         student     7             learn
1          1         principal   1             lead
1          4         mentor      1             train teachers
1          5         trainee     4             learn teaching
1          6         trainee     4             learn teaching
1          7         teacher     1             teach
2          8         student     9             learn
2          9         principal   9             lead
notes
--------------------------------------------------------------
note_id    obj_id    note
--------------------------------------------------------------
1          2         foo
2          2         bar
3          2         baz
4          3         lorem
5          8         ipsum
I need to write out the hierarchy and number of notes per user as follows:
-------------------------------------------------------------------------------------------
obj_id   notes  obj_path
-------------------------------------------------------------------------------------------
1        0      principal 1 (lead)
2        3      student 2 (learn) > teacher 7 (teach) > principal 1 (lead)
3        1      student 3 (learn) > teacher 7 (teach) > principal 1 (lead)
4        0      mentor 4 (train teachers) > principal 1 (lead)
5        0      trainee 5 (learn teaching) > mentor 4 (train teachers) > principal 1 (lead)
6        0      trainee 6 (learn teaching) > mentor 4 (train teachers) > principal 1 (lead)
7        0      teacher 7 (teach) > principal 1 (lead)
8        1      student 8 (learn) > principal 2 (lead)
9        0      principal 9 (lead)
For this, I understand that I need to use a loop as follows:
declare cur cursor for 
select obj_id from users order by root_id 
open cur
declare @obj_id int
    fetch next from cur into @id
    while (@@FETCH_STATUS = 0)
    begin
        select obj_role from users where obj_id = @obj_id
        fetch next from cur into @obj_id
    end
close cur
deallocate cur
This is what I have until now, but I do not understand how to go from here. Can someone help me on my way?
 
    