2012-08-01 209 views
2

我有一個名爲Module的表。 表結構任務,比如:SQL SERVER 2008樹形查詢

ModuleID  ModuleName  ParentID 

    1   System Manage  0 
    2   Database Manage  1 
    3   Area Manage   1 
    4   Basic Setting  0 

我想通過SQL語句得到下面的結果。

ModuleID  ModuleName  ParentMoudle 
    1    System Manage  0 
    2    Database Manage System Manage 
    3    Area Manage  System Manage 
    4    Basic Setting  0 

我是一個sql新手。非常感謝!

回答

1

父子關係可以通過LEFT OUTER JOIN實現並查詢同一個表。

 select m.moduleid,m.modulename,COALESCE(p.modulename,0) from table as m 
     left outer join table as p on m.moduleid = p.module.id 
+1

注意,如果您的層次結構是有史以來唯一一個一級深度,這隻會工作。如果層數不確定,則必須使用CTE或新的HierarchyID類型。 – 2012-08-01 08:18:41

0

這應該工作:

;WITH Tree AS 
(
    SELECT *, CAST(NULL AS VARCHAR(25)) AS ParentName 
     FROM @TT 
    WHERE ParentID IS NULL 
    UNION ALL 
    SELECT Fam.*,Tree.ModuleName AS ParentName 
     FROM @TT AS Fam 
    INNER JOIN Tree 
     ON Fam.ParentID = Tree.moduleID 
) 
SELECT * FROM Tree