| From: | "Erik Aronesty" <erik(at)zoneedit(dot)com> | 
|---|---|
| To: | <pgsql-sql(at)postgresql(dot)org> | 
| Subject: | datediff script | 
| Date: | 2004-04-21 14:13:25 | 
| Message-ID: | 04af01c427aa$ddb75640$cd855140@h2ttp | 
| Views: | Whole Thread | Raw Message | Download mbox | Resend email | 
| Thread: | |
| Lists: | pgsql-sql | 
This is a not-quite complete implementation of the SY/MS sql datediff.  The
months_between function can be extrapolated from it as well.  I looked for
it on forums, etc. and all I found were people complaining about the lack of
an example.  Please post fixes/changes or a link to a better one... if you
know of it.
CREATE OR REPLACE FUNCTION public.datediff(varchar, timestamp, timestamp)
  RETURNS int4 AS
'
DECLARE
 arg_mode alias for $1;
 arg_d2 alias for $2;
 arg_d1 alias for $3;
BEGIN
if arg_mode = \'dd\' or arg_mode = \'d\' or arg_mode = \'y\' or arg_mode =
\'dy\' or arg_mode = \'w\' then
 return cast(arg_d1 as date) - cast(arg_d2 as date);
elsif arg_mode = \'ww\' then
        return ceil( ( cast(arg_d1 as date) - cast(arg_d2 as date) ) / 7.0);
elsif arg_mode = \'mm\' OR arg_mode = \'m\' then
 return 12 * (date_part(\'year\',arg_d1) - date_part(\'year\',arg_d2))
      + date_part(\'month\',arg_d1) - date_part(\'month\',arg_d2)
             + case when date_part(\'day\',arg_d1) >
date_part(\'day\',arg_d2)
                    then 0
                    when date_part(\'day\',arg_d1) =
date_part(\'day\',arg_d2) and cast(arg_d1 as time) >= cast(arg_d2 as time)
                    then 0
                    else -1
               end;
elsif arg_mode = \'yy\' OR arg_mode = \'y\' OR arg_mode = \'yyyy\' then
 return (cast(arg_d1 as date) - cast(arg_d2 as date)) / 365;
end if;
END;
'
  LANGUAGE 'plpgsql' VOLATILE;
| From | Date | Subject | |
|---|---|---|---|
| Next Message | abief_ag_-postgresql | 2004-04-21 14:43:12 | Trigger calling a function HELP ME! | 
| Previous Message | ogjunk-pgjedan | 2004-04-21 12:20:52 | Re: Order by YYYY MM DD in reverse chrono order trouble |