I have an existing WebApp that uses a Postgres (9.4) db. The application has a fairly standard permissions structure, with Users belonging to Groups, and Levels/Departments within the organization in a hierarchy (a Level has a Parent-Level).
The relevant part of the DataModel is:
create table level(level_id int primary key, parent_level int);
create table grouplevel(level_id int, group_id int);
create table usergroup(user_id int, group_id int);
The app uses Postgres' WITH RECURSIVE
feature to traverse the Level tree, to collect a hierarchical list of level_id
s that a User has Group permission on. In other words, it lists the top-tier Levels first, then their children, and the children's children in that order
SELECT
level_id
FROM
(
WITH RECURSIVE tree(level_id, root)AS(
SELECT
C .level_id,
C .parent_level
FROM
LEVEL C
LEFT JOIN LEVEL P ON C .level_id = P .parent_level
WHERE
P .level_id IN(
SELECT
GL.level_id
FROM
GROUPLEVEL GL
JOIN USERGROUP UG ON(GL.GROUP_ID = UG.GROUP_ID)
WHERE
USER_ID = 1
)
UNION
SELECT
tree.level_id,
root
FROM
tree
INNER JOIN LEVEL ON tree.root = LEVEL .level_id
)SELECT
*
FROM
tree
)AS T
UNION
(
SELECT
GL.level_id
FROM
GROUPLEVEL GL
JOIN USERGROUP UG ON(GL.GROUP_ID = UG.GROUP_ID)
WHERE
USER_ID = 1
)
Now we are implementing the App with a MSSQL back-end - is there any way to achieve the same kind of recursive/hierarchical listing in MSSQL?