Sql 递归

时间:2020-09-18 01:13:23   收藏:0   阅读:31
 with temp(id,name,curlevel,hasChild)
 as 
 (
 --初始查询
 select id,name,1 curlevel,1 hasChild from tabName pc with(nolock)
 where Disabled = 0 and ParentId is null
 union all
 --查询子语句
 select pchild.id id,pchild.name name,p.curlevel +1 curlevel,
 (case when exists(select 1 from tabName where ParentId = pchild.id) then 1 else 0 end) hasChild 
 from tabName pchild with(nolock) 
 inner join temp p on pchild.ParentId = p.id and pchild.Disabled = 0
 )
 select * from temp

  

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!