Sqlserver 递归查询

WITH AS短语,也叫做子查询部分(subquery factoring),可以让你做很多事情,定义一个SQL片断,该SQL片断会被整个SQL语句所用到。有的时候,是为了让SQL语句的可读性更高些,也有可能是在UNION ALL的不同部分,作为提供数据的部分。

特别对于UNION ALL比较有用。因为UNION ALL的每个部分可能相同,但是如果每个部分都去执行一遍的话,则成本太高,所以可以使用WITH AS短语,则只要执行一遍即可。

with as 查询的模板 

 with test as 
 (
select * fromunion all
select  t.* from 表 t,test m  where t.ID=m.ParentId
 )
 select distinct * from  test order by  ID

自上到下

  with test as 
 (
select cb_ProjectAccount.* from cb_ProjectAccount  
union all
select  t.* from cb_ProjectAccount t,test m  where t.ParentProjectAccountGUID=m.ProjectAccountGUID
 )
 select distinct * from  test order by  ProjectAccountGUID

自下到上递归

  ;with test as 
 (
select cb_ProjectAccount.* from cb_ProjectAccount  
union all
select  t.* from cb_ProjectAccount t,test m  where m.ProjectAccountGUID=t.ParentProjectAccountGUID
 )
 select distinct * from  test order by  ProjectAccountGUID desc

 

posted @ 2020-03-06 17:40  hello-*-world  阅读(742)  评论(0编辑  收藏  举报