ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 使用SQL SERVER 2005/2008 递归CTE查询树型结构

使用SQL SERVER 2005/2008 递归CTE查询树型结构

原创 Linux操作系统 作者:iSQlServer 时间:2009-07-20 14:55:33 0 删除 编辑

  我们经常遇到树型结构,把它们显示在一个类似TreeView控件上的情况。这时我们可以使用Recursive Common Table Expressions(CTE)实现。下面是一个简单的Family Tree 示例:

 

   1:  DECLARE @TT TABLE (ID int,Relation varchar(25),Name varchar(25),ParentID int)
   2:  INSERT @TT SELECT 1,' Great GrandFather' , 'Thomas Bishop', null  UNION ALL
   3:  SELECT 2,'Grand Mom', 'Elian Thomas Wilson' , 1  UNION ALL
   4:  SELECT 3, 'Dad', 'James Wilson',2 UNION ALL
   5:  SELECT 4, 'Uncle', 'Michael Wilson', 2 UNION ALL
   6:  SELECT 5, 'Aunt', 'Nancy Manor', 2 UNION ALL
   7:  SELECT 6, 'Grand Uncle', 'Michael Bishop', 1 UNION ALL
   8:  SELECT 7, 'Brother', 'David James Wilson',3 UNION ALL
   9:  SELECT 8, 'Sister', 'Michelle Clark', 3 UNION ALL
  10:  SELECT 9, 'Brother', 'Robert James Wilson', 3 UNION ALL
  11:  SELECT 10, 'Me', 'Steve James Wilson', 3 
  12:   
  13:  ----------Query---------------------------------------
  14:  ;WITH FamilyTree 
  15:  AS(  
  16:    SELECT *, CAST(NULL AS VARCHAR(25)) AS ParentName, 0 AS Generation  FROM @TT  
  17:      WHERE ParentID IS NULL        
  18:      UNION ALL       
  19:     SELECT Fam.*,FamilyTree.Name AS ParentName, Generation + 1   FROM @TT AS Fam   
  20:        INNER JOIN FamilyTree    ON Fam.ParentID = FamilyTree.ID
  21:   )SELECT * FROM FamilyTree

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/16436858/viewspace-609722/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-10-17

  • 博文量
    1319
  • 访问量
    2074069