Generate a random date in Oracle with DBMS_RANDOM

2020-02-08 15:46发布

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?

4条回答
趁早两清
2楼-- · 2020-02-08 16:31

here is one more option to generate date going back from now where 365 - days quanitity to move back from today, 'DD.MM.YYYY'- mask

to_char(sysdate-dbms_random.value()*365, 'DD.MM.YYYY')

查看更多
聊天终结者
3楼-- · 2020-02-08 16:38

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
查看更多
冷血范
4楼-- · 2020-02-08 16:40

If you want to see it's logic, you can also use this code.

  create or replace procedure genDate(result out nvarchar2) IS
  year  number;
  month  number;
  day  number;
Begin
  year:=FLOOR(DBMS_RANDOM.value(2000,2100));
  month:=FLOOR(DBMS_RANDOM.value(1,12));
  IF month=2 and (year/4)=0 and (year/100)!=0 then
    day:=FLOOR(DBMS_RANDOM.value(1,29));
  ELSIF month=2 or (year/100)=0 then
    day:=FLOOR(DBMS_RANDOM.value(1,28));
  ELSIF MOD(month,2)=1 then
    day:=FLOOR(DBMS_RANDOM.value(1,31));
  ELSIF MOD(month,2)=0 and month!=2 then
    day:=FLOOR(DBMS_RANDOM.value(1,30));
  END IF;  
  result:=month||'-'||day||'-'||year;
End;
查看更多
在下西门庆
5楼-- · 2020-02-08 16:45

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

查看更多
登录 后发表回答