Oracle PL/SQL Tutorial/Function Procedure Packages/Recursive Functions

Материал из SQL эксперт
Перейти к: навигация, поиск

Recursion

SQL>
SQL> create or replace function factorial (i NUMBER)
  2  return NUMBER
  3  is
  4  begin
  5      if i = 1
  6      then
  7          return 1;
  8      else
  9          return i*factorial(i-1);
 10      end if;
 11  end;
 12  /
Function created.


Recursive functions

SQL>
SQL> set serveroutput on
SQL> set echo on
SQL>
SQL> CREATE OR REPLACE FUNCTION Factorial(p_MyNum INTEGER) RETURN NUMBER AS
  2  BEGIN
  3       IF p_MyNum = 1 THEN -- Checking for last value to process of n-1
  4            RETURN 1;
  5       ELSE
  6            RETURN(p_MyNum * Factorial(p_MyNum-1)); -- Recursive
  7       END IF;
  8  END;
  9  /
Function created.
SQL>
SQL> BEGIN
  2       DBMS_OUTPUT.PUT_LINE(factorial(10));
  3  END;
  4  /
3628800
PL/SQL procedure successfully completed.