Difference between two dates in postgresql

穿精又带淫゛_ 提交于 2019-12-20 04:16:36

问题


Function:

CREATE FUNCTION diff(d1 date,d2 date) RETURNS int AS $$
BEGIN
IF d1 = NULL THEN
RETURN SELECT extract(year from age(current_date,d2));
ELSE
RETURN SELECT extract(year from age(d1,d2));
END IF;
END
$$ language plpgsql;

My requirement is to find the difference between two dates in years. So, I write the above function. Here, if d1 is NULL then it is assigned with current date. But, it produce error like as shown below.

ERROR:  syntax error at or near "SELECT"
LINE 1: SELECT  SELECT extract(year from age(current_date, $1 ))
QUERY:  SELECT  SELECT extract(year from age(current_date, $1 ))
CONTEXT:  SQL statement in PL/PgSQL function "diff" near line 4 

Does any one help me to solve this problem.


回答1:


Try :

date_part('year',age(coalesce(d1,current_date), d2))::int;

age(d1,d2) function returns the number of years, months, and days between two dates in following format:

xxx year(s) xxx mon(s) xxx day(s).

from this output using date_part() to pick the only the year difference. and also no need to put if statement to handle NULL as I have added coalesece which returns first NON Null value, So if d1 is NULL it return cuurent_date

Function Structure:

CREATE OR REPLACE FUNCTION diff(d1 date,d2 date) RETURNS int AS $$
BEGIN

 RETURN date_part('year',age(coalesce(d1,current_date), d2))::int;
END
$$ language plpgsql;

Function Call:

select * from diff(null,'2010-04-01');
select * from diff('2012-10-01','2010-04-01');


来源:https://stackoverflow.com/questions/35168963/difference-between-two-dates-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!