試してみてください:
date_part('year',age(coalesce(d1,current_date), d2))::int;
age(d1,d2) 関数は、2つの日付の間の年、月、日数を次の形式で返します。
xxx year(s) xxx mon(s) xxx day(s).
date_part()を使用してこの出力から 年差のみを選択します。また、NULLを処理するためにifステートメントを配置する必要もありません。 coaleseceを追加したので これは最初のNON Nullを返します 値、つまりd1 NULLです cuurent_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');