Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random date in Oracle with DBMS_RANDOM

I have this anonymous block:

DECLARE
   V_DATA   DATE;
BEGIN
   V_DATA := '01-GEN-2000';

   HR.STATISTICHE.RATINGOPERATORI (V_DATA);
   COMMIT;
END;

but I would to generate the date in a random way. How can I do?

like image 704
sharkbait Avatar asked Jul 03 '13 13:07

sharkbait


People also ask

How do I insert date in YYYY MM DD in Oracle?

The TO_DATE function allows you to define the format of the date/time value. For example, we could insert the '3-may-03 21:02:44' value as follows: insert into table_name (date_field) values (TO_DATE('2003/05/03 21:02:44', 'yyyy/mm/dd hh24:mi:ss')); Learn more about the TO_DATE function.

How do I create a date variable in Oracle?

Answer: We can declare a date variable in PL/SQL with the syntax given below: DECLARE stdt DATE := to_date ('06/06/2006', 'DD/MM/YYYY');

What is DBMS_RANDOM in Oracle?

Oracle DBMS_RANDOM package provides functionality for generating random numbers or strings as part of an SQL statement or PL/SQL procedure. The DBMS_RANDOM Package stored procedures include: NORMAL — Returns random numbers in a standard normal distribution.


2 Answers

To generate random date you can use

select to_date('2010-01-01', 'yyyy-mm-dd')+trunc(dbms_random.value(1,1000)) from dual

or for random datetime

select to_date('2010-01-01', 'yyyy-mm-dd')+dbms_random.value(1,1000) from dual
like image 38
Kamil Mętrak Avatar answered Oct 19 '22 01:10

Kamil Mętrak


You can generate random dates between two dates ,as displayed in the query below .Random Dates are generated between 1-jan-2000 and 31-dec-9999

  SELECT TO_DATE(
              TRUNC(
                   DBMS_RANDOM.VALUE(TO_CHAR(DATE '2000-01-01','J')
                                    ,TO_CHAR(DATE '9999-12-31','J')
                                    )
                    ),'J'
               ) FROM DUAL;

OR you can use

SELECT TO_DATE (
              TRUNC (
                     DBMS_RANDOM.VALUE (2451545, 5373484) 
                    )
                , 'J'
              )
  FROM DUAL

In the above example ,the first value is 01-Jan-2000 and the second value id 31-dec-9999

like image 190
Gaurav Soni Avatar answered Oct 19 '22 00:10

Gaurav Soni