postgresql中两个日期之间的差异

Difference between two dates in postgresql

函数:

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;

我的要求是找出两个日期之间的年差。所以,我写了上面的函数。此处,如果 d1 为 NULL,则为其分配当前日期。但是,它会产生如下所示的错误。

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

有没有人帮我解决这个问题。

尝试:

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

age(d1,d2) 函数 returns 计算两个日期之间的年数、月数和天数,格式如下:

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

从这个输出中使用 date_part() 来选择唯一的年份差异。并且也不需要放置 if 语句来处理 NULL 因为我添加了 coalesece 其中 return 第一个 NON Null 值,所以如果 d1NULL它returncuurent_date

函数结构:

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;

函数调用:

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