I can’t quite get this right.. my function looks like:
create or replace function myfunc(integer, varchar(25), varchar(25), integer, integer) returns numeric as $$
declare var_return numeric;
begin
select sum(a+ b) / sum(a + b + c)
from mytable
where col1 = $1
and col2 = $2
and col3 = $3
and col4 between $4 AND $5
into var_return;
exception when division_by_zero then return 0.0;
return coalesce(var_return, 0.0);
end;
$$ language plpgsql;
But when I do select myfunc(123, 'foo', 'bar', 1, 10); I see:
ERROR: control reached end of function without RETURN
CONTEXT: PL/pgSQL function "myfunc"
Why does this happen? Clearly I want to catch when the select statement encounters a case where a + b + c equals 0 and return 0.
The EXCEPTION clause pertains to the entire BEGIN block, and runs until the END. That is, Postgres understands you to have written this:
Move your “RETURN COALESCE…” above the EXCEPTION line, and try again.