概念:
程序调用自身的编程技巧称为递归( recursion)。
一个过程或函数在其定义或说明中又直接或间接调用自身的一种方法,它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策 略只需少量的程序就可描述出解题过程所需要的多次重复计算,大大地减少了程序的代码量。递归的能力在于用有限的语句来定义对象的无限集合。用递归思想写出 的程序往往十分简洁易懂。
一般来说,递归需要有边界条件、递归前进段和递归返回段。当边界条件不满足时,递归前进;当边界条件满足时,递归返回。
注意:
(1) 递归就是在过程或函数里调用自身;
(2) 在使用递增归策略时,必须有一个明确的递归结束条件,称为递归出口。
1、阶乘
create or replace function f_calc_factorial(n pls_integer)
return pls_integer is
e_app exception;
begin
case
when n is null then
raise e_app;
when n in (0, 1) then
return 1;
else
return f_calc_factorial(n - 1) * n;
end case;
exception
when e_app then
raise_application_error(-20000, '请输入要计算阶乘的整数');
when others then
raise;
end f_calc_factorial;
2、汉诺塔
create or replace procedure p_hanot(P_disk_num int,
a varchar2,
b varchar2,
c varchar2) as
e_app exception;
begin
case
when (P_disk_num is null or P_disk_num = 0) then
raise e_app;
when P_disk_num = 1 then
dbms_output.put_line('把磁盘' || P_disk_num || '从柱子' || a || '移到柱子' || c);
else
p_hanot(P_disk_num - 1, a, c, b);
dbms_output.put_line('把磁盘' || P_disk_num || '从柱子' || a || '移到柱子' || c);
p_hanot(P_disk_num - 1, b, a, c);
end case;
exception
when e_app then
raise_application_error(-20000, '请输入大于等于1的磁片个数');
when others then
raise;
end p_hanot;
3、菲波那契数列(后一项等于前2项的和,第一位=1,第二位=1)