2016-07-08 61 views
1

在此先感謝您的幫助。我對MS SQL數據庫還是比較陌生的,但是我想知道爲什麼我下面的MSSQL遞歸查詢沒有返回我期望的值。我已經完成了我的研究,最後是我提出的代碼。比方說,我有以下表...遞歸查詢SQL Server不按預期工作

CategoryID ParentID SomeName 
1    0   hmm 
2    0   err 
3    0   woo 
4    3   ppp 
5    4   ttt 

我期待下面的查詢返回3 4 5我基本上是想獲得它下面的類ID的層次結構列表中的自我包容的基礎上,分類ID我通過遞歸查詢。感謝您的幫助。

GO 
WITH RecursiveQuery (CategoryID) 
AS 
(
-- Anchor member definition 
    SELECT a.CategoryID 
    FROM [SomeDB].[dbo].[SomeTable] AS a 
    WHERE a.ParentID = CategoryID 
    UNION ALL 
-- Recursive member definition 
    SELECT b.CategoryID 
    FROM [SomeDB].[dbo].[SomeTable] AS b 
    INNER JOIN RecursiveQuery AS d 
     ON d.CategoryID = b.ParentID 
) 
-- Statement that executes the CTE 
SELECT o.CategoryID 
FROM [SomeDB].[dbo].[SomeTable] AS o 
INNER JOIN RecursiveQuery AS d 
    ON d.CategoryID = 3 
GO 
+0

'WHERE a.ParentID = 0'(第一個選項可能是更好的,如果要創建的某種根鑑於此第二個主要適用) ,'WHERE b.ParentID = d.theID' –

+0

我想最後的選擇可能來自'RecursiveQuery'。 'd.theID'不會產生橫切值'3',它將成爲所有id的列表。所以filter = 3會給你一條記錄。 –

+0

正如@IvanStarostin所說,你的錨定成員定義並不是記錄。主播應該是一個作爲你的出發點的記錄。 –

回答

2

如果你想從具體根椐:

DECLARE @rootCatID int = 3 

;WITH LessonsTree (CatID) 
AS 
(
    SELECT a.CategoryID 
    FROM [EducationDatabase].[dbo].[LessonCategory] AS a 
    WHERE a.CategoryID = @rootCatID ---<<< 

    UNION ALL 

    SELECT b.CategoryID 
    FROM LessonsTree as t 
    INNER JOIN [EducationDatabase].[dbo].[LessonCategory] AS b 
     ON b.ParentID = t.CatID 
) 
SELECT o.* 
FROM LessonsTree t 
INNER JOIN [EducationDatabase].[dbo].[LessonCategory] AS o 
    ON o.CategoryID = t.CatID 
+0

@debonaire你應該把它標記爲答案,如果是的話。 –

+0

謝謝你現在要做。你可以批准編輯變量名稱非常感謝 – debonaire

0

正如評論指出,錨不受限制。最簡單的辦法就是添加繞圈在錨

with RecursiveQuery (theID) 
AS 
(
    SELECT a.ParentID --root id=parentid to include it and to prevent an extra trip to LessonCategory afterwards 
    FROM [LessonCategory] AS a 
    WHERE a.ParentID = 3 --restriction here 
    UNION ALL 
    SELECT b.CategoryID 
    FROM [LessonCategory] AS b 
    INNER JOIN RecursiveQuery AS d 
     ON d.theID = b.ParentID 
) 
SELECT* from RecursiveQuery 

另一種選擇是讓遞歸查詢是一般(沒有受限制的錨),並讓它保持rootid爲好。然後在CTE查詢可以在rootid限制

with RecursiveQuery 
AS 
(
    SELECT a.ParentID theID, a.ParentID RootID 
    FROM [LessonCategory] AS a  
    UNION ALL 
    SELECT b.CategoryID, d.RootID 
    FROM [LessonCategory] AS b 
    INNER JOIN RecursiveQuery AS d 
     ON d.theID = b.ParentID 
) 
SELECT theID from RecursiveQuery where RootID = 3 
+0

非常感謝你的建議。將考慮到這一點。乾杯! – debonaire