递归关于进行树形结构的查询:
一:简单的树形结构代码。
-- with一个临时表(括号中是你要查询的列名)
with temp(ID,PID,Name,curLevel)
as
(
--1:初始查询(这里的PID=-1 在我的数据中是最底层的根节点)
select ID,PID,Name,1 as level from dbo.T_ACL_OU
where Deleted = 0 and PID = -1
union all
--2:递归条件
select a.ID,a.PID,a.Name, b.curLevel+1from T_ACL_OU a --3:这里的临时表和原始数据表都必须使用别名,不然递归的时候不知道查询的是那个表的列
inner join
temp b
on ( a.PID=b.id) --这个关联关系很重要,一定要理解一下谁是谁的父节点
)
select * from temp --4:递归完成后 一定不要少了这句查询语句 否则会报错
二:带缩进的树形机构
with temp(ID,PID,Name,curLevel)
as
(
--初始查询
select ID,PID,Name,1 as curLevel from dbo.T_ACL_OU
where Deleted = 0 and PID = -1
union all
--递归条件
select a.ID,a.PID,
convert(nvarchar(100),CONVERT(nvarchar(100), REPLICATE (' ', b.curLevel+1)+a.Name)) as Name , b.curLevel+1
--这里的 REPLICATE函数非常重要,用于缩进空格用。不懂得可以在SQLserver中选中后按F1键
from T_ACL_OU a
inner join
temp b
on ( a.PID=b.id)
)
select ID,PID,Name,curLevel from temp
三:查询是否有子节点
with temp(ID,PID,HandNo,Name,curLevel,pLevel,haveChild)
as
(
--初始查询
select ID,PID,HandNo,Name,1 as level,0 as pLevel,1 as haveChild from dbo.T_ACL_OU
where Deleted = 0 and PID = -1
union all
--递归条件
select a.ID,a.PID,a.HandNo,a.Name, b.curLevel+1,b.curLevel,haveChild
= (case when exists(select 1 from T_ACL_OU where T_ACL_OU.PID=a.id) then 1 else 0 end)
--(select 1 from T_ACL_OU where exists(select 1 from T_ACL_OU where a.PID=b.id))
from T_ACL_OU a
inner join
temp b
on ( a.PID=b.id)
)
select * from temp order by pLevel
这3段代码可以直接复制使用,修改一下表名和要查询的列名基本上都是通用的.