24 Nov 2014

PL/SQL recursive calls: recursion in Oracle


PL/SQL does support recursion via function calls. Recursion is the act of a function calling itself, and a recursive call requires PL/SQL to create local copies of its memory structures for each call.

PL/SQL allows sub procedures or functions to be called recursively. The tutorial example below shows you how to calculate factorial values with a recursive sub function.

CREATE OR REPLACE
PROCEDURE FACTORIAL_TEST( N NUMBER )
AS
FUNCTION FACTORIAL( N NUMBER )
  RETURN NUMBER
AS
BEGIN
  IF N <= 1 THEN
    RETURN 1;
  ELSE
    RETURN N*FACTORIAL(N-1);
  END IF;
END;
BEGIN
  DBMS_OUTPUT.PUT_LINE('Factorial of '||N||' = ' || TO_CHAR(FACTORIAL(N)));
END; 

DECLARE
  N NUMBER;
BEGIN
  N := 10;

  FACTORIAL_TEST(
    N => N
  );
END;

Factorial of 10 = 3628800

No comments:

Post a Comment