Question

I have the following tables

UserRights - This table contains extra role selected for the user has been defined. 
RoleRights - Default roles defined by the users
UserRole - To map the user and their default role
Roles - Role name (ID = Primary Key)

CONDITION: User has to be part of a ROLE, only then they can select extra roles if required.

| UserRights |
|---------------|
| UserID (FK)   |


| RoleRights    |
|---------------|
| RoleID (FK)   |


| UserRole      |
|---------------|
| UserID (FK)   |
| RoleID (FK)   |

Now, consider if the RoleRights has been defined with 37 rows for a specific role and UserRight table has 1 row defined by the user for a specific user. The mapping table which is UserRole has the definition which maps USERID and the ROLEID.

We need to construct the output which result in 38 rows, i.e. take 37 rows from =RoleRights table and 1 row from UserRights table based on UserID.

How do we go about constructing SQL query to result this output?

Was it helpful?

Solution

It's easiest to do it with UNION because it allows you to write 2 independet queries.

select UR.UserRightID 
from UserRights UR 
where UR.UserID = @UserID

union

select RR.RoleRightID 
from RoleRights RR
where exists 
    (select * from UserRole UR1 where UR1.RoleID = RR.RoleID and UR1.UserID = @UserID)

You can use UNION ALL of you want to get all records even if they have the same value from both queries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top