Sql使用with+as递归查询

Sql递归原理

递归最少包括两个查询(也被称为成员)。第一个查询为定点成员,定点成员只是一个返回有效表的查询,用于递归的基础或定位点。第二个查询被称为递归成员,使该查询成为递归成员的是对递归引用时触发(递归表.id与该表的pid)。在逻辑上,可以将其理解为是前一个查询语句的子集。递归查询没有显式的递归终止条件,只有当第二个递归查询返回空结果集或是超出了递归次数的最大限制时才停止递归。递归次数上限的方法是使用MAXRECURION:后接OPTION (MAXRECURSION 0) --排除限值

Sql递归案例

SQL Server中

  1. 日期范围递归:
    with wt_temp(orderby,mydate) as
    (select 1 orderby,convert(varchar(10),'2020-01-01',120)
        union all
        select orderby+1, convert(varchar(10),dateadd(DD,1,mydate),120) 
        from wt_temp 
        where mydate < '2020-01-05'
        ) 
    select * from wt_temp
  2. 树查询:一般用于菜单/权限/分类等。
    create table [#temp](
     [id] [int] null,
     [pid] [int] null,
     [name] [nchar](10)
    )
    go
    insert into #temp values(1,0,'a')
    insert into #temp values(2,0,'b')
    insert into #temp values(3,1,'c')
    insert into #temp values(4,1,'d')
    insert into #temp values(5,2,'e')
    insert into #temp values(6,3,'f')
    insert into #temp values(7,3,'g')
    insert into #temp values(8,4,'h')
    go
    --由子结点递归父项
    with my1 as(select * from #temp where id = 1
     union all select #temp.* from my1, #temp where my1.id = #temp.pid
    )
    select * from my1 
    --由父结点递归子项
    with my2 as(select * from #temp where id = 8
     union all select #temp.* from my2, #temp where my2.pid = #temp.id
    )
    select * from my2

Oracle中

使用语法:connect by (prior) t.parent_id = (prior) t.id start with id = ??

  prior 只有一个,在不同的位置查不同的结果.prior 在前查前辈,prior在后查后生。 

with wt_temp(orderby,mydate) as
(select 1 orderby,convert(varchar(10),'2020-01-01',120)
    union all
    select orderby+1, convert(varchar(10),dateadd(DD,1,mydate),120) 
    from wt_temp 
    where mydate < '2020-01-05'
    ) 
select * from wt_temp
原文地址:https://www.cnblogs.com/zhengxianfa/p/14299022.html