gpt4 book ai didi

sql - CTE 遍历备份层次结构?

转载 作者:行者123 更新时间:2023-12-03 21:24:51 28 4
gpt4 key购买 nike

我可以在分层数据模型中找到给定记录的所有子项(请参阅下面的代码),但我不确定如何使用给定的子 ID 遍历备份父/子链。谁能指出我正确的方向来弄清楚如何做到这一点?这在 Linq to SQL 中也可能吗?

WITH TaskHierarchy (TaskID, [Subject], ParentID, HierarchyLevel, HierarchyPath) AS
(
-- Base case
SELECT
TaskID,
[Subject],
ParentID,
1 as HierarchyLevel,
CONVERT(VARCHAR(MAX),'/') AS HierarchyPath
FROM Task
WHERE TaskID = 2

UNION ALL

-- Recursive step
SELECT
t.TaskID,
t.Subject,
t.ParentID,
th.HierarchyLevel + 1 AS HierarchyLevel,
CONVERT(varchar(MAX),th.HierarchyPath + CONVERT(VARCHAR(32),t.ParentID) + '/') AS HierarchyPath
FROM Task t
INNER JOIN TaskHierarchy th ON
t.ParentID = th.TaskID
)

SELECT *
FROM TaskHierarchy
ORDER BY HierarchyLevel, [Subject]

最佳答案

啊,我想通了:

WITH Hierarchy(TaskID, [Subject], ParentID, IsProject, HLevel)
AS
(
SELECT
TaskID,
[Subject],
ParentID ,
IsProject,
0 as HLevel
FROM
Task
WHERE
TaskID = 59

UNION ALL

SELECT
SubDepartment.TaskID,
SubDepartment.[Subject],
SubDepartment.ParentID ,
SubDepartment.IsProject,
HLevel + 1
FROM
Task SubDepartment
INNER JOIN
Hierarchy ParentDepartment
ON
SubDepartment.TaskID = ParentDepartment.ParentID
)

SELECT
TaskID,
[Subject],
ParentID,
IsProject,
HLevel
FROM
Hierarchy
ORDER BY
HLevel DESC

关于sql - CTE 遍历备份层次结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/584904/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com