__SQL PL/SQL Codes to Calculate Factorial of a Number__We all know factorial of a non-negative number n, is the product of all positive integers less than or equal to n. For example factorial of 4 is 4*3*2*1=24, factorial of 5 is 5*4*3*2*1=120.

Now from oracle how we can get the factorial value. Below is the some ways,

**Way 1: Using PL/SQL**

The following is an example of calculating factorial of 9 and 6.

Code :

SQL> create or replace function factorial_calc(value integer) 2 return integer 3 as 4 minus1 pls_integer; 5 product pls_integer; 6 begin 7 dbms_output.enable(999999); 8 minus1 := value - 1; 9 if ( minus1 > 0 ) 10 then 11 product := value*factorial_calc(minus1); 12 return product; 13 end if; 14 return value; 15 end factorial_calc; 16 / Function created. SQL> declare 2 value integer; 3 begin 4 value:=factorial_calc(9); 5 dbms_output.put_line(value); 6 end; 7 / PL/SQL procedure successfully completed. SQL> set serverout on SQL> / 362880 362880 PL/SQL procedure successfully completed. SQL> list 4 4* value:=factorial_calc(9); SQL> c/9/6 4* value:=factorial_calc(6); SQL>/ 720 PL/SQL procedure successfully completed. SQL> select factorial_calc(12) from dual; FACTORIAL_CALC(12) ------------------ 479001600

Way 2: Using SQL.

Way 2: Using SQL.

Code :

SQL> select round(exp(sum(ln(n)))) 2 from ( 3 select level AS n 4 from dual 5 connect by level <= &n 6 ) 7 ; Enter value for n: 6 old 5: connect by level <= &n new 5: connect by level <= 6 ROUND(EXP(SUM(LN(N)))) ---------------------- 720

Arju