Tuesday, July 17, 2012

The secret to date subtraction in Oracle

Psst... Hey you--yes, you! The one aimlessly searching Google trying to find a way to subtract two Oracle datetime fields for your query or for connecting to Crystal Reports. The code is actually quite straight forward--I cannot believe so many websites are obtuse about it.

     trunc(nvl(end_date,sysdate),-begin_date) will return the difference in days

     trunc(nvl(end_date,sysdate),-begin_date)*24 will return the difference in hours

     trunc(nvl(end_date,sysdate),-begin_date)/356 will return the difference in years

It is that simple. If you try to wait until after the query and use Crystals Datediff("d",end,beginning) you are going to be in for a surprise. DateDiff doesn't really work well...

No comments:

Post a Comment