05.11.2015 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

538<br />

CHAPTER 12 ■ DATATYPES<br />

9 from dual )<br />

10 /<br />

DAY HOUR MINUTE SECOND<br />

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

380 10 20 29.878<br />

Additionally, we’ve already seen the NUMTOYMINTERVAL <strong>and</strong> the NUMTODSINTERVAL for creating<br />

YEAR TO MONTH <strong>and</strong> DAY TO SECOND intervals. I find these functions to be the easiest way to<br />

create instances of INTERVAL types—over <strong>and</strong> above the string conversion functions. Rather<br />

than concatenate a bunch of numbers representing the days, hours, minutes, <strong>and</strong> seconds<br />

representing some interval together, I’d rather add up four calls to NUMTODSINTERVAL to do the<br />

same.<br />

The INTERVAL type can be used to store not just durations, but “times” as well in a way. For<br />

example, if you want to store a specific date <strong>and</strong> time, you have the DATE or TIMESTAMP types.<br />

But what if you want to store just the time 8:00 am? The INTERVAL type would be h<strong>and</strong>y for that<br />

(the INTERVAL DAY TO SECOND type in particular).<br />

INTERVAL YEAR TO MONTH<br />

The syntax for INTERVAL YEAR TO MONTH is straightforward:<br />

INTERVAL YEAR(n) TO MONTH<br />

where N is an optional number of digits to support for the number of years <strong>and</strong> varies from<br />

0 to 9, with a default of 2 (to store a number of years from 0 to 99). It allows you to store any<br />

number of years (up to nine digits’ worth, anyway) <strong>and</strong> months. The function I prefer to use to<br />

create INTERVAL instances of this type is NUMTOYMINTERVAL. For example, to create an interval of<br />

five years <strong>and</strong> two months, we can use the following:<br />

ops$tkyte@ORA10G> select numtoyminterval(5,'year')+numtoyminterval(2,'month')<br />

2 from dual;<br />

NUMTOYMINTERVAL(5,'YEAR')+NUMTOYMINTERVAL(2,'MONTH')<br />

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

+000000005-02<br />

Or, using a single call <strong>and</strong> the fact that a year has 12 months, we can use the following:<br />

ops$tkyte@ORA10G> select numtoyminterval(5*12+2,'month')<br />

2 from dual;<br />

NUMTOYMINTERVAL(5*12+2,'MONTH')<br />

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

+000000005-02<br />

Either approach works well. Another function, TO_YMINTERVAL, can be used to convert a<br />

string into a year/month INTERVAL type:

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

Saved successfully!

Ooh no, something went wrong!