Reputation: 1726
I'm using SQL Server 2012 and have 3 tables that I'm trying to pull data from: Role, DependentRoles, and ActiveRole:
I need to return data for a given Role
and data for any DependentRole
for that role as well. For instance, If the Role
table has ids 1-15 and the DependentRoles
table is populated like so:
we find that for the RoleId
of 2, it has 2 DependentRoles
; 4 & 5. So if I want to find all the Roles that are assigned to a given role, my sql looks like this:
SELECT dr.*
FROM DependentRoles dr
INNER JOIN [Role] r ON dr.ChildRoleId = r.RoleId
INNER JOIN ActiveRole ar ON r.RoleId = ar.RoleId
WHERE ar.RoleId = 4
which produces this:
which tells me that Roles 5, 7, 9, 2, 10, 11, & 12 all depend on Role 4. What I now need is to return the RoleName
for the ParentRoleId
and ChildRoleId
. I can't just add r.RoleName
to the sql above because it returns just the Child RoleName, I need both. I'd like to return DependentRoleId
, ParentRoleId
, ParentRoleName
, ChildRoleId
, ChildRoleName
:
2 5 Role-E 4 Role-D
3 7 Role-G 4 Role-D
5 9 Role-I 4 Role-D
8 2 Role-B 4 Role-D
I tried joining on the Role
table again but to the ParentRoleId
but I'm not getting any results for ParentRoleName
:
SELECT dr.DependentRoleId, dr.ParentRoleId, r2.RoleName AS 'ParentRoleName', r.RoleId, r.RoleName AS 'ChildRoleName'
FROM DependentRoles dr
INNER JOIN [Role] r ON dr.ChildRoleId = r.RoleId
LEFT OUTER JOIN [Role] r2 ON dr.ParentRoleId = r.RoleId
INNER JOIN ActiveRole ar ON r.RoleId = ar.RoleId
WHERE ar.RoleId = 4
Any ideas on how I can get my desired results? I must add that I will be translating this into linq statements so I'm trying to avoid CTE and other methods that I cannot convert.
Upvotes: 1
Views: 48
Reputation: 585
In your OUTER JOIN
your ON
is on r and not r2. Furthermore, if you always have a parent role, you should use INNER JOIN
so something like this should work :
SELECT dr.DependentRoleId, dr.ParentRoleId AS 'ParentRoleID',
r2.RoleName AS 'ParentRoleName', dr.ChildRoleId AS 'ChildRoleID' , r.RoleName AS 'ChildRoleName'
FROM DependentRoles dr
INNER JOIN [Role] r ON dr.ChildRoleId = r.RoleId
INNER JOIN [Role] r2 ON dr.ParentRoleId = r2.RoleId
INNER JOIN ActiveRole ar ON r.RoleId = ar.RoleId
WHERE ar.RoleId = 4
Upvotes: 2