Created
August 15, 2012 06:51
-
-
Save wgzhao/3357205 to your computer and use it in GitHub Desktop.
create simple date diff function ,can return the number of years/months/days between two date
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | |
create or replace function datediff(m text,d1 date,d2 date) returns int as $$ | |
declare | |
d1_year int; | |
d1_month int; | |
d2_year int; | |
d2_month int; | |
day int; | |
begin | |
select extract(year from d1) into d1_year; | |
select extract(month from d1) into d1_month; | |
select extract(year from d2) into d2_year; | |
select extract(month from d2) into d2_month; | |
if m = 'year' then | |
return (d2_year - d1_year); | |
elsif m = 'month' then | |
return (d2_year - d1_year) * 12 + (d2_month - d1_month); | |
elsif m = 'day' then | |
select d2 - d1 into day; | |
return day; | |
end if; | |
end; | |
$$ language plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment