SQL SERVER 2008 CTE生成结点的FullPath
吴秀波胡子被剪,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
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!!
点击进行留言回复
相关文章:
-
-
sql某个日期是当年的第几周
/* *周一作为一周的开始 *当年的1月1号所在的周算作第一周 */ CREATE function GetWeekIndexFirstDate ( @...
[阅读全文]
-
-
数据库SQL---范式
1、数据冗余导致的问题:冗余存储、更新异常、插入异常、删除异常。 2、函数依赖:一种完整性约束。 在关系模式r(R)中,α属于R,β属于R。 1)α函数...
[阅读全文]
-
-
数据库SQL---查询
1、查询所有列 select *from emp;--*表示所有的,from emp表示从emp表中查询。 2、查询指定列 select empno,e...
[阅读全文]
-
-
-
-
-
网友评论