Sql 递归

 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

  

posted @ 2020-09-14 16:11  微笑代表淡定.Net  阅读(98)  评论(0编辑  收藏  举报