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.
Try :
age(d1,d2)
function returns the number of years, months, and days between two dates in following format:from this output using
date_part()
to pick the only the year difference. and also no need to put if statement to handleNULL
as I have addedcoalesece
which returns firstNON Null
value, So ifd1
isNULL
it returncuurent_date
Function Structure:
Function Call: