SQL SERVER 2008 CTE生成結點的FullPath

iSQlServer發表於2010-01-19
      SQL SERVER 2008 使用CTE是經常的事兒,有時我們想儲存一些冗餘資料,像每個結點的FullPath。好的,現在來看如何生成FullPath:
DECLARE @tbl TABLE 
  (  
   Id int 
  ,ParentId int 
  ) 
 
INSERT  INTO @tbl 
        ( Id, ParentId ) 
VALUES  ( 0, NULL ) 
,       ( 8, 0 ) 
,       ( 12, 8 ) 
,       ( 16, 12 ) 
,       ( 17, 16 ) 
,       ( 18, 17 ) 
,       ( 19, 17 ) 
 
; 
WITH  abcd 
        AS ( 
              -- anchor 
            SELECT   id 
                    ,ParentID 
                    ,CAST(id AS VARCHAR(100)) AS [Path] 
            FROM    @tbl 
            WHERE   ParentId IS NULL 
            UNION ALL 
              --recursive member 
            SELECT  t.id 
                   ,t.ParentID 
                   ,CAST(a.[Path] + ',' + CAST( t.ID AS VARCHAR(100)) AS varchar(100)) AS [Path] 
            FROM    @tbl AS t 
                    JOIN abcd AS a ON t.ParentId = a.id 
           ) 
SELECT  Id ,ParentID ,[Path] 
FROM    abcd 
WHERE   Id NOT IN ( SELECT  ParentId 
                    FROM    @tbl 
                    WHERE   ParentId IS NOT NULL ) 
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } 返回:

Id          ParentID    Path
----------- ----------- ----------------------
18          17          0,8,12,16,17,18
19          17          0,8,12,16,17,19

 

就這麼簡單,實際上有Sql server 2008中HierarchyType 也能很好的解決這個問題。我將在後面寫一些關於HierarchyType的Post.

希望這篇POST對您有幫助。

Author Peter Liu http://wintersun.cnblogs.com

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/16436858/viewspace-625443/,如需轉載,請註明出處,否則將追究法律責任。

相關文章