PL/SQL function to generate a random number
Q. Write a PL/SQL function that generates a random number between 1 and 10.
Answer:
This type of code is used in cryptographic applications. Consider a pseudo- random number generator and its output is difficult to predict. So the idea behind this is generate a true random numbers to use as initial value (ie. the seed) and used in the cryptographic applications.
Step1:
DECLARE x number;
BEGIN
SELECT trunc(dbms_random.value(1,10)) INTO x
FROM dual;
dbms_output.put_line(x);
END;
/
Step2:
DECLARE seed number;
n number:=&number;
BEGIN seed := EXP(TO_NUMBER(TO_CHAR(SYSDATE,'ss'))/59)-1;
seed := 1/(seed - TRUNC(seed));
seed := seed - TRUNC(seed);
n:=trunc(n/10)-1;
dbms_output.put_line(trunc(seed,n)*power(10,n));
END;
/
Output: