2014-09-01 87 views
7

我有一個SQL Server提供一個二叉樹2014表:二進制搜索查詢使用SQL

UserID ParentUserID Position 
---------------------------- 
1  Null   Null  <-- ROOT 
2  1   Left 
3  1   Right <-- Last Right for ID=1 (CTE query return 3) 
4  2   Left 
5  4   Left 
6  5   Left 
7  6   Left  <-- Last Left for ID=1 (CTE query return 6) 

要獲得最後只剩ID和一個右ID我使用CTE查詢:

; with left_hand_recurse as 
(
     select UserID 
     ,  ParentUserID 
     ,  1 as depth 
     from Table1 where ParentUserID is null 
     union all 
     select child.UserID 
     ,  child.ParentUserID 
     ,  parent.depth + 1 
     from left_hand_recurse parent 
     join Table1 child 
     on  parent.UserID = child.ParentUserID 
       and position = 'Left' 
) 
select top 1 * 
from left_hand_recurse 
order by 
     depth desc 
; 

; with right_hand_recurse as 
(
     select UserID 
     ,  ParentUserID 
     ,  1 as depth 
     from Table1 where ParentUserID is null 
     union all 
     select child.UserID 
     ,  child.ParentUserID 
     ,  parent.depth + 1 
     from right_hand_recurse parent 
     join Table1 child 
     on  parent.UserID = child.ParentUserID 
       and position = 'Right' 
) 
select top 1 * 
from right_hand_recurse 
order by 
     depth desc 
; 

它工作正常。這樣我可以得到最後UserID在左側或右側的根目錄(ParentUserID == 1

我需要修改CTE查詢以獲得相同的結果但我想作爲參數傳遞@ParentUserID特定ParentUserID

如何實現這一目標?

回答

2

只要改變這條線在每個CTE:

from Table1 where ParentUserID is null 

到:

from Table1 where ParentUserID = @ParentId 
+1

將有助於它向別人解釋爲什麼工作,而不是原來的版本? – 2014-09-01 20:41:55

+0

我試過了,工作不正確。如果我沒有表「正確」值,則查詢將返回該LastRight的位置。 – 2014-09-01 20:49:11