SQL Server 2005开始,我们可以直接通过CTE来支持递归查询,CTE即公用表表达式
百度百科
公用表表达式(CTE),是一个在查询中定义的临时命名结果集将在from子句中使用它。每个CTE仅被定义一次(但在其作用域内可以被引用任意次),并且在该查询生存期间将一直生存。可以使用CTE来执行递归操作。创建的语法是:
with <name of you cte>(<column names>)
as(
<actual query>
)
select * from <name of your cte>
生成数据
--菜单目录结构表
create table tb_menu(
id int not null, --主键id
title varchar(50), --标题
parent int --parent id
);
--父菜单
insert into tb_menu(id, title, parent) values(1, '父菜单1',null);
insert into tb_menu(id, title, parent) values(2, '父菜单2',null);
insert into tb_menu(id, title, parent) values(3, '父菜单3',null);
insert into tb_menu(id, title, parent) values(4, '父菜单4',null);
insert into tb_menu(id, title, pa