回答は、却下的な「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
私は理解しません - これは、各レベルが識別されたテーブル全体を返します。どうしたの? –
yah私は以前のコメントを残念に思ったレベルについて忘れてしまった今、私はこのテーブルに私の望む結果を問い合わせる必要がある – rahularyansharma