当前位置: 移动技术网 > IT编程>数据库>MSSQL > SQL SERVER 2008 CTE生成结点的FullPath

SQL SERVER 2008 CTE生成结点的FullPath

2017年12月08日  | 移动技术网IT编程  | 我要评论

吴秀波胡子被剪,goldfarm,华尼托踩踏马特乌斯

好的,现在来看如何生成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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网