05.11.2015 Views

Apress.Expert.Oracle.Database.Architecture.9i.and.10g.Programming.Techniques.and.Solutions.Sep.2005

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

528<br />

CHAPTER 12 ■ DATATYPES<br />

ops$tkyte@ORA10G> select dt, dt+numtoyminterval(1,'month')<br />

2 from (select to_date('28-feb-2001','dd-mon-yyyy') dt from dual )<br />

3 /<br />

DT<br />

DT+NUMTOYMINTERVAL(1<br />

-------------------- --------------------<br />

28-feb-2001 00:00:00 28-mar-2001 00:00:00<br />

Notice how the resulting date is not the last day of the next month, but rather the same<br />

day of the next month. It is arguable that this behavior is acceptable, but consider what<br />

happens when the resulting month doesn’t have that many days:<br />

ops$tkyte@ORA10G> select dt, dt+numtoyminterval(1,'month')<br />

2 from (select to_date('30-jan-2001','dd-mon-yyyy') dt from dual )<br />

3 /<br />

select dt, dt+numtoyminterval(1,'month')<br />

*<br />

ERROR at line 1:<br />

ORA-01839: date not valid for month specified<br />

ops$tkyte@ORA10G> select dt, dt+numtoyminterval(1,'month')<br />

2 from (select to_date('30-jan-2000','dd-mon-yyyy') dt from dual )<br />

3 /<br />

select dt, dt+numtoyminterval(1,'month')<br />

*<br />

ERROR at line 1:<br />

ORA-01839: date not valid for month specified<br />

In my experience, that makes using a month interval in date arithmetic impossible in<br />

general. A similar issue arises with a year interval: adding one year to February 29, 2000,<br />

results in a runtime error as well, because there is no February 29, 2001.<br />

Getting the Difference Between Two DATEs<br />

Another frequently asked question is, “How do I retrieve the difference between two dates?”<br />

The answer is deceptively simple: you just subtract them. This will return a number representing<br />

the number of days between the two dates. Additionally, you have the built-in function<br />

MONTHS_BETWEEN that will return a number representing the number of months—including<br />

fractional months—between two dates. Lastly, with the INTERVAL types, you have yet another<br />

method to see the elapsed time between two dates. The following SQL query demonstrates<br />

the outcome of subtracting two dates (showing the number of days between them), using the<br />

MONTHS_BETWEEN function <strong>and</strong> then the two functions used with INTERVAL types:<br />

ops$tkyte@ORA10G> select dt2-dt1 ,<br />

2 months_between(dt2,dt1) months_btwn,<br />

3 numtodsinterval(dt2-dt1,'day') days,<br />

4 numtoyminterval(months_between(dt2,dt1),'month') months<br />

5 from (select to_date('29-feb-2000 01:02:03','dd-mon-yyyy hh24:mi:ss') dt1,<br />

6 to_date('15-mar-2001 11:22:33','dd-mon-yyyy hh24:mi:ss') dt2<br />

7 from dual )

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!