I want to combine privileges from the user and their roles in a stored procedure. To do so currently I am running many queries. The first gets the roles the user has. Then a query to get the privileges for each role. Then a query to get the privileges for the user. Then I combine them all from the code. I would like to be able to do all that from a stored procedure. I have not ever worked with stored procedures so I do not know if it is even possible.
Hopefully the diagram will help you understand what I am trying to do.
I started to write one but it is not near finished or functional.
CREATE PROCEDURE get_privileges
@userId INT
AS
SET NOCOUNT ON;
SELECT
role_id
FROM
user_role
INNER JOIN
role ON user_role.role_id = role.id
WHERE
user_id = @userId;
-- For each role
SELECT
privilege_id as id, name
FROM
role_privilege
INNER JOIN
privilege ON role_privilege.privilege_id = privilege.id
WHERE
role_id = ${roleId}
SELECT
privilege_id as id, name
FROM
user_privilege
INNER JOIN
privilege ON user_privilege.privilege_id = privilege.id
WHERE
user_id = @userId;
What do I need to do to finish the procedure?
Looping through the results of the first select. No clue how to do this.
Combining the results. Found that this could be done by making a temp table and then pushing the result sets from each query to it. Is there a better way?
Sample:
user table
+----+----------+
| id | username |
+----+----------+
| 1 | caleb |
+----+----------+
role table
+------+----------+
| role | name |
+------+----------+
| 1 | admin |
| 2 | standard |
+------+----------+
privilege table
+-----------+---------------+
| privilege | name |
+-----------+---------------+
| 1 | CREATE_USER |
| 2 | DELETE_USER |
| 3 | ADMIN_VIEW |
| 4 | STANDARD_VIEW |
| 5 | NOTHING |
+-----------+---------------+
user_privilege table
+---------+--------------+
| user_id | privilege_id |
+---------+--------------+
| 1 | 1 |
+---------+--------------+
user_role table
+---------+---------+
| user_id | role_id |
+---------+---------+
| 1 | 1 |
+---------+---------+
role_privilege table
+---------+--------------+
| role_id | privilege_id |
+---------+--------------+
| 1 | 2 |
| 1 | 3 |
| 2 | 4 |
+---------+--------------+
Expected result for user_id = 1
+--------------+-------------+
| privilege_id | name |
+--------------+-------------+
| 1 | CREATE_USER |
| 2 | DELETE_USER |
| 3 | ADMIN_VIEW |
+--------------+-------------+

