sqlserver递归查询数据

查询所有的:select Name,BusinessUnitId,ParentBusinessUnitId,ParentBusinessUnitIdName from BusinessUnit

--查询某一节点的所有子节点

with cte(Name,BusinessUnitId,ParentBusinessUnitId,ParentBusinessUnitIdName)
as
(
select Name,BusinessUnitId,ParentBusinessUnitId,ParentBusinessUnitIdName from BusinessUnit where Name='会员管理与服务部'
union all
select b.Name,b.BusinessUnitId,b.ParentBusinessUnitId,b.ParentBusinessUnitIdName
from cte A ,BusinessUnit B where B.ParentBusinessUnitId = A.BusinessUnitId and A.ParentBusinessUnitId <>B.BusinessUnitId
)
select Name,BusinessUnitId,ParentBusinessUnitId,ParentBusinessUnitIdName
from cte
OPTION(MAXRECURSION 0)

 

 

 

--查询某一节点的所有父节点
with cte (Name,BusinessUnitId,ParentBusinessUnitId,ParentBusinessUnitIdName)
as
(
select Name,BusinessUnitId,ParentBusinessUnitId,ParentBusinessUnitIdName from BusinessUnit where Name='会员管理与服务部'
union all
select b.Name,b.BusinessUnitId,b.ParentBusinessUnitId,b.ParentBusinessUnitIdName
from cte A ,BusinessUnit B where a.ParentBusinessUnitId = b.BusinessUnitId and a.ParentBusinessUnitId <> a.BusinessUnitId
)
select Name,BusinessUnitId,ParentBusinessUnitId,ParentBusinessUnitIdName
from cte
OPTION(MAXRECURSION 0)
posted @ 2012-11-09 13:51  jamin  阅读(275)  评论(0编辑  收藏  举报