Generate a random date in Oracle with DBMS_RANDOM

后端 未结 4 1262
不知归路
不知归路 2020-12-14 11:16

I have this anonymous block:

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

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


        
相关标签:
4条回答
  • 2020-12-14 11:42

    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')

    0 讨论(0)
  • 2020-12-14 11:49

    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
    
    0 讨论(0)
  • 2020-12-14 11:52

    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

    0 讨论(0)
  • 2020-12-14 11:53

    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;
    
    0 讨论(0)
提交回复
热议问题