oracle数据库中函数的递归调用

若有下面的表结构AAAA,用一个字段prev_id表示记录的前后顺序,要对其排序,须要用的递归函数函数

ID PREV_ID CONT
99   a
23 54 d
21 23 e
54 33 c
33 99 b
32 45 g
45 21 f

 

 

 

 

 

 

如:spa

 create or replace function sequen(cid number)
 return number is
 pid number(2);
 begin
 select prev_id into pid from aaaa where id=cid;
  if pid is null then return 1;
  else return sequen(pid)+1; --递归调用本身
  end if;
 end;排序

查询语句 select sequen(id) sq, t.* from AAAA t order by sq递归

结果:ci

SQ ID PREV_ID CONT
1 99   a
2 33 99 b
3 54 33 c
4 23 54 d
5 21 23 e
6 45 21 f
7 32 45 g
相关文章
相关标签/搜索