Tuesday, August 10, 2010

How to create a Oracle PL/SQL function that returns random numbers?

How to create a function that returns random numbers?

Can you imagine an Oracle PL/SQL Function that returns Random Numbers? This is very useful for testing features in multiple scenarios.
Oracle comes with a built-in package “dbms_random.value” for this purpose. The function will return a random float number between a given range.

Eg:
Create a input with YES and NO answers. Test both without changing any underlying criteria. To test the changes within a webpage, just refresh the page a few times without any change to the database or inputs.

CREATE OR REPLACE FUNCTION GET_RANDOM
RETURN NUMBER
IS
      P_RETVALUE    NUMBER;
BEGIN

      P_RETVALUE := 0;
    
      SELECT floor(mod(dbms_random.value(3,10),2))
      INTO P_RETVALUE
      FROM DUAL;
    
      RETURN P_RETVALUE;

EXCEPTION
WHEN OTHERS THEN
      RETURN 0;
END;
/

COMMIT
/


The function is called using the below call:
select get_random() from dual

By changing the value in the MOD function, it is possible to have more than 2 values. Also by adding an IF .. THEN ELSE loop after the SELECT STATEMENT, it is possible to have non-numeric values.

Eg:
IF P_RETVALUE = 0 THEN
      RETURN "Equal"
ELSE IF P_RETVALUE = 1 THEN
      RETURN "Less"
ELSE
      RETURN "More"
END IF