use test set nocount on if object_id ( ' Dept ' , ' U ' ) is not null drop table Dept go create table Dept(ID int ,ParentID int ,Name varchar ( 20 )) insert into Dept select 1 , 0 , ' AA ' insert into Dept select 2 , 1 , ' BB ' insert into
use test
set nocount on
if object_id('dept','u') isnotnull
drop table dept
go
create table dept(id int,parentid int,name varchar(20))
insert into dept select 1,0,'aa'
insert into dept select 2,1,'bb'
insert into dept select 3,1,'cc'
insert into dept select 4,2,'dd'
insert into dept select 5,3,'ee'
insert into dept select 6,0,'ff'
insert into dept select 7,6,'gg'
insert into dept select 8,7,'hh'
insert into dept select 9,7,'ii'
insert into dept select 10,7,'jj'
insert into dept select 11,9,'kk'
go
select*from dept;
--查询树状结构某节点的上级所有根节点。
with cte_root(id,parentid,name)
as
(
--起始条件
select id,parentid,name from dept where id='1'--查询条件
union all
--递归条件
select a.ID,a.ParentID,a.NAME from Dept a
innerjoin cte_root b --执行递归,这里就要理解下了
on a.ID=b.ParentID --根据基础表条件查询子节点(a.ID),通过CTE递归找到其父节点(b.ParentID)。
) --可以和下面查询子节点的cte_child对比。
select*from cte_root ;
--查询树状结构某节点下的所有子节点。
with cte_child(ID,ParentID,NAME)
as
(
--起始条件
select ID,ParentID,NAME
from Dept
where Name ='II'--列出父节点查询条件
union all
--递归条件
select a.ID,a.ParentID,a.NAME
from Dept a
inner join
cte_child b
on a.ID=b.ParentID --根据查询到的父节点(a.Parent),通过CTE递归查询出其子节点(b.ID)
)
select*from cte_child --可以改变之前的查询条件'II'再测试结果
ID ParentID Name
----------- ----------- --------------------
10 AA
21 BB
31 CC
42 DD
53 EE
60 FF
76 GG
87 HH
97 II
107 JJ
119 KK
ID ParentID NAME
----------- ----------- --------------------
97 II
76 GG
60 FF
ID ParentID NAME
----------- ----------- --------------------
97 II
119 KK
聚彩手机商城系统,是一款专业于手机销售的独立手机网店系统,他拥有众多的手机参数选项,以及傻瓜式的设置选项,让您可以在5分钟内建立起专业而强大的手机销售网站。他拥有多套模版可以实时切换,前台拥有新闻中心、手机中心、配件中心、软件下载、手机报价、发货查询、保修查询、分店查询、产品的对比功能,代理与加盟的申请等功能,他拥有完善的会员中心,会员等级设置等,集成在线支付接口,超强SEO,可以设置所有页面的t
0
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号