SqlServer的递归查询 也就是 with cte查询

表结构 技术分享

表数据技术分享

 

SQL如下

with lmenu 
as
(
 select name,id,1 as lv,cast(Name as nvarchar(max)) as name1, cast(ROW_NUMBER()over(order by getdate()) as nvarchar(10)) as orderid   from Table2 where Table2.ParentId=0 
  Union all
  select a.Name ,a.ID,(b.lv+1) as lv,cast( REPLICATE(‘  ‘,b.lv*2)+ a.name as nvarchar(max)) as name1,
  cast( ( b.orderid+‘.‘+ cast(ROW_NUMBER()over(Order by GETDATE() ) as nvarchar(5))) as nvarchar(10)) as   orderid 
  from Table2 as a inner join lmenu as b on a.ParentId=b.id
)
select * from lmenu  order by   orderid ;

查询结果:

技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。