Friday 7 September 2012

function DateDiff

create or replace function DateDiff(DatePart varchar, StartDate date, EndDate date)
return number
as
result    number;
sType    char(1);
begin
    sType := substr(upper(DatePart), 1, 1);
    if sType = 'S' then
        result := trunc(86400 * (EndDate - StartDate));
    end if;
    if sType = 'H' then
        result := trunc(((86400 * (EndDate - StartDate)) / 60) / 60);
    end if;
    if sType = 'D' then
        result := trunc((((86400 * (EndDate - StartDate)) / 60) / 60) / 24);
    end if;
    if sType = 'W' then
        result := trunc(((((86400 * (EndDate - StartDate)) / 60) / 60) / 24) / 7);
    end if;
    if sType = 'Y' then
        result := trunc(months_between(EndDate, StartDate) / 12);
    end if;
    if sType = 'N' then
        result := trunc((86400 * (EndDate - StartDate)) / 60);
    end if;
    if sType = 'M' then
        if upper(DatePart) like 'MI%' then
            result := trunc((86400 * (EndDate - StartDate)) / 60);
        else
            result := trunc(months_between(EndDate, StartDate));
        end if;
    end if;
return result;
exception when others then return null;
end;

No comments:

Post a Comment