Recursion versus Iteration
Dissimilar the iteration, recursion is not crucial to PL/SQL programming. Any problem which can be solved using recursion can be solving using the iteration. Also, the iterative version of the subprogram is typically easier to design than the recursive version. Though, the recursive version is typically simpler, smaller, and hence easier to debug. Compare the functions below that calculate the nth Fibonacci number:
-- recursive version
FUNCTION fib (n POSITIVE) RETURN INTEGER IS
BEGIN
IF (n = 1) OR (n = 2) THEN
RETURN 1;
ELSE
RETURN fib(n - 1) + fib(n - 2);
END IF;
END fib;
-- iterative version
FUNCTION fib (n POSITIVE) RETURN INTEGER IS
pos1 INTEGER := 1;
pos2 INTEGER := 0;
cum INTEGER;
BEGIN
IF (n = 1) OR (n = 2) THEN
RETURN 1;
ELSE
cum := pos1 + pos2;
FOR i IN 3..n LOOP
pos2 := pos1;
pos1 := cum;
cum := pos1 + pos2;
END LOOP;
RETURN cum;
END IF;
END fib;
The recursive version of the Fibonacci is more graceful than the iterative version. Though, the iterative version is more accurate; it runs faster and uses less storage. That is as each recursive call needs an additional time and memory. As the number of recursive calls gets bigger, so does the difference in effectiveness. Still, if you expect the number of recursive calls to be little, you may choose the recursive version for its readability.