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 |
如:
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
结果:
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 |