SQL SERVER 2008 CTE生成結點的FullPath。本站提示廣大學習愛好者:(SQL SERVER 2008 CTE生成結點的FullPath)文章只能為提供參考,不一定能成為您想要的結果。以下是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 )
前往:
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