create package fib_pkg as function fib_iteration(n number) return number; function fib_recursion(n number) return number; end fib_pkg; / Package created. create package body fib_pkg as function fib_iteration(n number) return number is first number := 0; second number := 1; current number; begin for i in 3 .. n loop current := first + second; first := second; second := current; end loop; return current; end fib_iteration; function fib_recursion(n number) return number is begin if n = 1 or n = 2 then return n - 1; end if; return fib_pkg.fib_recursion(n - 1) + fib_pkg.fib_recursion(n - 2); end fib_recursion; end fib_pkg; / Package body created. set serveroutput on var n number exec :n := fib_pkg.fib_iteration(10); PL/SQL procedure successfully completed. print n N ---------- 34 exec :n := fib_pkg.fib_recursion(10); PL/SQL procedure successfully completed. print n N ---------- 34

Now, we are seeing the Oracle PL/SQL version for generating the Fibonacci Sequence.

No need to mention that I used SQL*Plus to create/execute the codes.

We created a package `FIB_PKG`

to hold both iterative and recursive versions.

Note that on Line No. 31 I have qualified the function calls with the package name as well.

Though this is not a mandatory one, it is a good practice.

If we want, we can create them as a stand-alone functions as well, instead of encapsulating in the package.

create function fib_iteration(n number) return number is first number := 0; second number := 1; current number; begin for i in 3 .. n loop current := first + second; first := second; second := current; end loop; return current; end fib_iteration; / Function created. create function fib_recursion(n number) return number is begin if n = 1 or n = 2 then return n - 1; end if; return fib_recursion(n - 1) + fib_recursion(n - 2); end fib_recursion; / Function created.

OK. The above functions just return nth term.

What if want n terms?

Arrays in PL/SQL is not as simple as what we saw in JavaScript and/or Perl.

So, it is not posted now.

If possible, let us see it some other day later.