答案是使用recusive「Common Table Expression」或CTE。這使您可以構建層次結構。下面是一個例子,修改,以符合您的結構,基於此頁上:http://msdn.microsoft.com/en-us/library/ms186243.aspx
WITH CategoryStructured (ParentCategoryID, CategoryID, Description, Status, Level)
AS
(
-- Anchor member definition
SELECT c.ParentCategoryID, c.CategoryID, c.Description, c.Status,
0 AS Level
FROM Category AS c
WHERE c.ParentCategoryID=0
UNION ALL
-- Recursive member definition
SELECT c.ParentCategoryID, c.CategoryID, c.Description, c.Status,
Level + 1
FROM Category AS c
INNER JOIN CategoryStructured AS c_parent
ON c.ParentCategoryID = c_parent.CategoryID
)
-- Statement that executes the CTE
SELECT distinct cs.ParentCategoryID, cs.CategoryID, cs.Description, cs.Status, cs.Level
FROM
CategoryStructured cs,
(SELECT level,ParentCategoryID,CategoryID from CategoryStructured WHERE (categoryID = 4) OR (level = 1 AND parentCategoryID = 4)) as thisCategory
WHERE cs.level BETWEEN thisCategory.level - 1 AND thisCategory.level+1
AND ((thisCategory.level != 0 AND cs.ParentCategoryID = thisCategory.ParentCategoryID)
OR cs.categoryID = thisCategory.ParentCategoryID
OR cs.ParentCategoryID = thisCategory.CategoryID
OR cs.CategoryID = thisCategory.CategoryID)
更新,以反映更新後的問題。
編輯我知道你能得到上述基本爲你工作與添加的不同,但我想到了一個更好的方式來處理這個問題後,我離開了聊天:
WITH CategoryStructured (ParentCategoryID, CategoryID, Description, Status, Level)
AS
(
-- Anchor member definition
SELECT c.ParentCategoryID, c.CategoryID, c.Description, c.Status,
0 AS Level
FROM Categories AS c
WHERE
(c.ParentCategoryID IS NULL AND c.categoryID = 7) -- when 7 is a top level category, then it is the root level
OR (c.categoryID = (SELECT c2.parentCategoryID FROM Categories c2 WHERE c2.categoryID = 7)) -- when 7 is some non-top level category, then 7's parent is the root
UNION ALL
-- Recursive member definition
SELECT c.ParentCategoryID, c.CategoryID, c.Description, c.Status,
Level + 1
FROM Categories AS c
INNER JOIN CategoryStructured AS c_parent
ON c.ParentCategoryID = c_parent.CategoryID
)
-- Statement that executes the CTE
SELECT cs.ParentCategoryID, cs.CategoryID, cs.Description, cs.Status, cs.Level
FROM
CategoryStructured cs
WHERE cs.level < 3
ORDER BY cs.level
它將只返回子女,子女,但我想父母,兄弟姐妹也 – rahularyansharma 2011-12-23 05:09:24
我不明白 - 這返回整個表,每個級別確定。有什麼問題? – 2011-12-23 05:24:30
我現在檢查它對不起之前的評論我忘了關於水平現在我不得不查詢這張表爲我想要的結果 – rahularyansharma 2011-12-23 05:27:31