2010-01-11 93 views
0

我想在SQL Server 2005中編寫一個遞歸CTE查詢,但得到了一組奇怪的結果。我的表是:SQL遞歸CTE查詢奇數結果集SQL Server 2005

PairID ChildID ParentID 
900  1  2  
901  2  3  
902  3  4  

這是我的CTE查詢:

WITH TESTER (PairID, 
      ChildID, 
      ParentID, 
      Level) 
AS (SELECT a.PairID, a.ChildID,a.ParentID, 0 AS Level 
    FROM BusinessHierarchy AS a 
    UNION ALL 
    SELECT b.PairID, b.ChildID, b.ParentID, oh.Level + 1 AS Level 
    FROM BusinessHierarchy AS b INNER JOIN 
    TESTER AS oh ON b.ChildID = oh.ParentID) 
SELECT 
     x.PairID, 
     x.ChildID, 
     x.ParentID, 
     x.Level 
FROM TESTER AS x 
ORDER BY x.Level, x.ChildID, x.ParentID 

好了,現在我得到一個數據集的回報,但是,它並不如預期的,因爲它包含以下重複方式:

PairID ChildID ParentID Level 
900  1  2  0 
901  2  3  0 
902  3  4  0 
... 

900  2  3  1 
901  3  4  1 
... 

900  3  4  2 

如果有人能向我解釋爲什麼會發生這種情況,我將如何糾正它,我將非常感激。

至於我的最後一個問題去,我會如何修改它與每個父母這樣的顯示初始childID的:

Original 
PairID ChildID ParentID Level 
900  1  2  0 
901  2  3  1 
902  3  4  2 

I want it displayed as: 
PairID ChildID ParentID Level 
900  1  2  0 
901  1  3  1 
902  1  4  2 

回答

1

你的問題是你的出發點。 CTE查詢的第一部分返回所有行(注意它們的級別全爲0)。

然後 - 您的查詢的下一部分將去,並獲取所有相關的行(這將添加到您的早期結果集)。

我也注意到,但是,你有4

,如果你做的ID沒有記錄,這裏是你會做什麼:

;WITH TESTER (PairID, ChildID, ParentID, Level) AS (
    SELECT 
     a.PairID, 
     a.ChildID, 
     a.ParentID, 
     0 AS Level 
    FROM BusinessHierarchy AS a 
    LEFT JOIN BusinessHierarchy a2 ON a.ParentID = a2.ChildID 
    WHERE a2.PairID is null 

    UNION ALL 

    SELECT 
     b.PairID, 
     b.ChildID, 
     b.ParentID, 
     oh.Level + 1 AS Level 
    FROM BusinessHierarchy AS b 
    INNER JOIN TESTER AS oh ON b.ParentID = oh.ChildID 
) 

SELECT 
    x.PairID, 
    x.ChildID, 
    x.ParentID, 
    x.Level 
FROM TESTER AS x 
ORDER BY x.Level, x.ChildID, x.ParentID 

而且,看到my answer to a similar question以顯示正確的排序順序(使用路徑)

+0

我跑了查詢但沒有結果。我認爲問題是'parentId爲null',這就是爲什麼我從我的版本發佈它。我已經閱讀了幾個論壇和版本/例子,只是不明白爲什麼這不起作用。 – flavour404 2010-01-11 22:55:26

+0

我的代碼假設你會添加一個id爲4的記錄。如果你不是,你必須有其他方式的起點。 – 2010-01-11 22:57:10

+0

看到我的修改後的答案,將在你的情況下工作(我回到桌子上,看看哪裏沒有兒童記錄)。 – 2010-01-11 22:59:57