一、简单的树形数据

-- 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:递归完成后 一定不要少了这句查询语句 否则会报错


效果如图:

SqlServer 递归查询树形数据_子节点

这里要注意的地方是注释中的 1——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


效果如图

SqlServer 递归查询树形数据_javascript_02

三:查询是否有子节点

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


效果如图

SqlServer 递归查询树形数据_递归_03