若有下面的表結構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 |