oracle中新建datediff()函數(shù)

datediff()是SQLServer的函數(shù),如果要在oracle中填寫此函數(shù),如下操作。

1.建CDate函數(shù)

CREATE OR REPLACE Function CDate(Datechar In Varchar2) Return Date Is
  ReallyDo Date;
Begin
  Select to_date(to_char(to_date(to_char(Datechar), 'YYYY-MM-DD HH24:MI:SS'),
                         'YYYY-MM-DD'),
                 'YYYY-MM-DD')
    Into ReallyDo
    From Dual;
  Return(ReallyDo);
End CDate;

2.建CDateTime函數(shù)

CREATE OR REPLACE Function CDateTime(Datechar In Varchar2) Return Date Is
  ReallyDo Date;
Begin
  Select to_date(to_char(to_date(to_char(Datechar), 'YYYY-MM-DD HH24:MI:SS'),
                         'YYYY-MM-DD HH24:MI:SS'),
                 'YYYY-MM-DD HH24:MI:SS')
    Into ReallyDo
    From Dual;
  Return(ReallyDo);
End CDateTime;

3.建Datediff函數(shù)

CREATE OR REPLACE Function Datediff(Datepart  In Varchar2,
                                    StartDate In Varchar2,
                                    EndDate   In Varchar2) Return Number Is
  ReallyDo Numeric;
Begin
  Select Case Upper(Datepart)
           When 'YYYY' Then
            Trunc(Extract(Year From CDate(EndDate)) -
                  Extract(Year From CDate(StartDate)))
           When 'M' Then
            Datediff('YYYY', StartDate, EndDate) * 12 +
            (Extract(Month From CDate(EndDate)) -
             Extract(Month From CDate(StartDate)))
           When 'D' Then
            Trunc(CDate(EndDate) - CDate(StartDate))
           When 'H' Then
            Datediff('D', StartDate, EndDate) * 24 +
            (to_Number(to_char(CDateTime(EndDate), 'HH24')) -
             to_Number(to_char(CDateTime(StartDate), 'HH24')))
           When 'N' Then
            Datediff('D', StartDate, EndDate) * 24 * 60 +
            (to_Number(to_char(CDateTime(EndDate), 'MI')) -
             to_Number(to_char(CDateTime(StartDate), 'MI')))
           When 'S' Then
            Datediff('D', StartDate, EndDate) * 24 * 60 * 60 +
            (to_Number(to_char(CDateTime(EndDate), 'SS')) -
             to_Number(to_char(CDateTime(StartDate), 'SS')))
           Else
            -29252888
         End
    Into ReallyDo
    From Dual;
  Return(ReallyDo);
End Datediff;

備注:oracle中利用日期間的加減運算如下

天:
ROUND(TO_NUMBER(END_DATE - START_DATE))
小時:
ROUND(TO_NUMBER(END_DATE - START_DATE) * 24)
分鐘:
ROUND(TO_NUMBER(END_DATE - START_DATE) * 24 * 60)
秒:
ROUND(TO_NUMBER(END_DATE - START_DATE) * 24 * 60 * 60)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容