Wednesday 16 November 2011

DB2 Date Functions

Part2
There are some arithmetic manipulation rules for datetime types in db2
  • Divisions and multiplications is not allowed.
  • Subtractions is allowed using date/time values, durations or labeled durations.
  • Addition is allowed using labeled durations or date/time durations.
Valid labeled durations are : YEAR, MONTH,DAY ,HOUR, MINUTE, SECOND , MICROSECOND.
Also you can use plural durations : YEARS , MONTHS , DAYS , HOURS , MINUTES , SECONDS,MICROSECONDS

Now here it is some arithmetic manipulation examples.

select current date + 2 year as MY_DATE from SYSIBM.SYSDUMMY1;
--(as MY_DATE is alias)
select current date + 10 days from SYSIBM.SYSDUMMY1;
select current date + 2 month + 4 days from SYSIBM.SYSDUMMY1;
select current date + (2+3) days from SYSIBM.SYSDUMMY1;
select current timestamp + 11 hours from SYSIBM.SYSDUMMY1;

As we all know also we can use VALUES statment.

values current date + 2 year ;
values current date + 10 days ;
values current date + 2 month + 4 days ;

When we need to get difference between two date/time , the result is date,time or timestamp duration.
For example :
select FIRSTNAME,
LASTNAME ,
DATE_OF_BIRTH,
CURRENT DATE - DATE_OF_BIRTH as AGE
from PERSON

In this example the result Age is in hours duration.
If I need to get difference in Year duration I need to write sql something like this
 select FIRSTNAME,
LASTNAME ,
DATE_OF_BIRTH,
YEAR(CURRENT date) - YEAR(DATE_OF_BIRTH) as AGE
from PERSON

No comments: