好的,現(xiàn)在來看如何生成FullPath:
復(fù)制代碼 代碼如下:
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
就這么簡(jiǎn)單,實(shí)際上有Sql server 2008中HierarchyType 也能很好的解決這個(gè)問題。我將在后面寫一些關(guān)于HierarchyType的Post.
希望這篇POST對(duì)您有幫助。
Author Peter Liu