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