答案是使用递归的“公用表表达式”或 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)
更新以反映您更新的问题。
edit 我知道您可以通过添加的独特功能使上述内容基本上为您工作,但我在离开聊天后想到了一种更好的方法来处理这个问题:
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