13
我可以在分層數據模型中找到給定記錄的所有子代(請參見下面的代碼),但我不確定如何使用給定的子ID遍歷父/子鏈。任何人都可以指出我在正確的方向弄清楚如何做到這一點?這在LINQ to SQL中可能嗎?CTE可以遍歷層次?
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]
感謝張貼您的解決方案!它節省了我幾個小時! – 2009-11-29 20:35:14