Posted By

geekzspot on 12/01/12


Tagged


Versions (?)

Oracle Random Dates within a range


 / Published in: SQL
 

To produce a random date within a specified date range or between two dates

  1. -- Here we use from 1-jan-2012 to 30-aug-2012
  2.  
  3. SELECT TO_DATE(TRUNC(DBMS_RANDOM.VALUE(TO_CHAR(TO_DATE('1-jan-2012'),'J'),TO_CHAR(TO_DATE('30-aug-2012'),'J'))),'J') FROM DUAL;
  4.  
  5.  
  6. -- To produce a random date within a specified number of days from today:
  7.  
  8. -- Here we use two weeks (14 days) allowing dates in the past as well as the future
  9.  
  10. SELECT SYSDATE+DBMS_RANDOM.VALUE(-14,14) FROM DUAL;
  11.  
  12.  
  13. -- Here we use three weeks (21 days) allowing dates only in the future
  14.  
  15. SELECT SYSDATE+DBMS_RANDOM.VALUE(1,14) FROM DUAL;
  16.  
  17.  
  18. -- Here we use a year (365 days) allowing dates only in the past
  19.  
  20. SELECT SYSDATE+DBMS_RANDOM.VALUE(-365,0) FROM DUAL;

Report this snippet  

You need to login to post a comment.