2010-01-01 83 views
2

我有一個表是這樣的:SQL服務器獲得父列表

id name parent_id 
1 ab1 3 
2 ab2 5 
3 ab3 2 
4 ab4 null 
5 ab5 null 
6 ab6 null 

我需要做一個查詢的輸入ID = 1(一個例子)和結果會是這樣:

id name parent_id 
5 ab5 null 
2 ab2 5 
3 ab3 2 
1 ab1 3 

(列出所有級別的所有父母都從項目id = 1開始)

回答

5

也許這樣的事情?

WITH parents(id,name,parent,level) 
    AS 
    (
    SELECT 
     ID, 
     NAME, 
     PARENT, 
     0 as level 
    FROM 
     TABLE 
    WHERE ID = 1 
    UNION ALL 
    SELECT 
     ID, 
     NAME, 
     PARENT, 
     Level + 1 
    FROM 
     TABLE 
    WHERE 
     id = (SELECT TOP 1 parent FROM parents order by level desc) 
    ) 
    SELECT * FROM parents