--由父項遞歸下級
with cte(id,parentid,text)
as
(--父項
select id,parentid,text from treevIEw where parentid = 450
union all
--遞歸結果集中的下級
select t.id,t.parentid,t.text from treevIEw
as
t
inner join cte
as
c on t.parentid = c.id
)
select id,parentid,text from cte
---------------------
--由子級遞歸父項
with cte(id,parentid,text)
as
(--下級父項
select id,parentid,text from treevIEw where id = 450
union all
--遞歸結果集中的父項
select t.id,t.parentid,t.text from treevIEw
as
t
inner join cte
as
c on t.id = c.parentid
)
select id,parentid,text from cte
參考:http://msdn.microsoft.com/zh-cn/library/ms186243.ASPx