I have two tables in my database schema that represent an entity having a many-to-many relationship with itself.
Role
---------------------
+RoleID
+Name
RoleHasChildRole
---------------------
+ParentRoleID
+ChildRoleID
Essentially, I need to to be able to write a query such that:
Given a set of roles, return the unique set of all related roles recursively.
This is an MSSQL 2008 Database.
EDIT:
A request for some sample data was required. So here goes:
RoleID Name
------------------------------------
1 'Admin'
2 'SuperUser'
3 'Lackey'
4 'Editor'
5 'CanEditSomething'
6 'CanDeleteSomething'
7 'CanCreateSomething'
8 'CanViewSomething'
ParentRoleID ChileRoleID
------------------------------------
1 5
1 6
1 7
1 8
2 4
4 5
4 8
So a query for the Admin role would return:
‘Admin’
‘CanEditSomething’
‘CanDeleteSomething’
‘CanCreateSomething’
‘CanViewSomething’
And a query for SuperUser would return:
‘SuperUser’
‘Editor’
‘CanViewSomething’
‘CanEditSomething’
Pretty common CTE usage:
This one only goes down the role tree. I leave making one that goes up as an exercise.
EDIT Looks like you only wanted to go down the tree anyway. This query does that just fine.
Returns the following results on your test data: