我有一个树结构表,我需要找到一个元素的完整路径,但同时,元素受权限限制
我有一张表tblMapping
map_id name parent_id
1 Root 0
2 Child 1 1
3 Child 2 1
4 Child 3 3
5 Child 4 4
6 Child 5 5
和tblPerms
表:
perm_id map_id
1 5
2 6
我正在使用以下CTE查询:
;WITH Hierarchy (map_id, name, parent_id, Path)
AS
(
SELECT
t.map_id, t.name, t.parent_id,
CAST(t.name AS varchar(max))
FROM
tblMapping t
LEFT OUTER JOIN
tblMapping t1 ON t1.map_id = t.parent_id
LEFT OUTER JOIN
tblPerms t2 ON t2.map_id = t1.map_id
WHERE
t1.map_id IS NULL
UNION ALL
SELECT
t.map_id, t.name,t.parent_id,
CAST(h.Path + '.' + t.name AS varchar(max))
FROM
Hierarchy h
INNER JOIN
tblMapping t ON t.parent_id = h.map_id
)
SELECT Path
FROM Hierarchy
WHERE Path is not null
OPTION (MAXRECURSION 0)
CTE查询将为我提供与Child 4.Child 5
我希望能够获得元素的完整路径,即使未设置权限:Root.Child 1.Child 3.Child 4.Child 5
有关如何解决此请求的任何想法?
谢谢!
答案 0 :(得分:3)
首先构建路径然后检查权限
WITH Hierarchy (map_id, name, parent_id, Path)
AS
(
SELECT
t.map_id, t.name, t.parent_id,
CAST(t.name AS varchar(max))
FROM
tblMapping t
LEFT OUTER JOIN
tblMapping t1 ON t1.map_id = t.parent_id
WHERE
t1.map_id IS NULL
UNION ALL
SELECT
t.map_id, t.name,t.parent_id,
CAST(h.Path + '.' + t.name AS varchar(max))
FROM
Hierarchy h
INNER JOIN
tblMapping t ON t.parent_id = h.map_id
)
SELECT Path
FROM Hierarchy h
JOIN tblPerms t2 ON t2.map_id = h.map_id
WHERE Path is not null
OPTION (MAXRECURSION 0);