Sqlserver递归查询所有上级或所有下级成员

版权声明:本文为博主原创文章,未经博主允许不得转载,如文章对您有帮助,请页面左侧随意打赏。 https://blog.csdn.net/smartsmile2012/article/details/80950919
--菜单目录结构表
create table tb_menu(
 id int not null, --主键id
 title varchar(50), --标题
 parent int --parent id
);

--查找所有上级节点
with cte_parent(id,title,parent)
as
( 
    select id,title,parent    from tb_menu    where id = 1   --列出子节点查询条件 
    union all 
    select a.id,a.title,a.parent    from tb_menu a    inner join     cte_parent b          --执行递归,这里就要理解下了 
    on a.id=b.parent   
)                        
select * from cte_parent;

----------------------------------------------
 
 
--查找下级节点带level
with cte_child(id,title,parent,level) 
as 
( 
    select id,title,parent,0 as level from tb_menu    where id = 1--列出父节点查询条件 
    union all 
    select a.id,a.title,a.parent,b.level+1 from tb_menu a 
    inner join  cte_child b on ( a.parent=b.id)   
)
 select  * from cte_child;

猜你喜欢

转载自blog.csdn.net/smartsmile2012/article/details/80950919