Creatinf icase function using
CREATE OR REPLACE FUNCTION public.icase(
cond1 boolean, res1 anyelement,
cond2 boolean, res2 anyelement,
conddefault anyelement)
RETURNS anyelement LANGUAGE 'sql' IMMUTABLE PARALLEL UNSAFE AS $BODY$
SELECT CASE WHEN $1 THEN $2 WHEN $3 THEN $4 ELSE $5 END;
$BODY$;
select
icase( false, 0, false, 0.,0.)
throws error
function icase(boolean, integer, boolean, numeric, numeric) does not exist
How to allow icase to accept mixed integer/numeric parameters?
2
Answers
Per the link:
https://www.postgresql.org/docs/current/xfunc-sql.html#XFUNC-SQL-POLYMORPHIC-FUNCTIONS
So:
Which when run does:
Though as you see it will coerce the output to a common suitable type.
Polymorphic types lead to a common, uniform data type.
Anyelement
will act as a placeholder for 4x the same type, and if you pass 3 different things (4th is the result type which will be adjusted to the 3 params), it’ll just give up.Anycompatible
won’t give up but rather attempt to convert the 3 different things to one common type, if it’s at all possible, and only if there’s only one unique way to convert them all. It will let you invoke the routine using a mix of types, but they’ll all end up converted.Overload your function instead if you want more control (and plan to stay on v12):
demo at db<>fiddle
With the 5 definitions above, any of the 8 possible combinations of
int
andnumeric
on any of the 3 positions gets resolved fine:If you wanted to mix parameter types between different calls, not within a single invocation, your definition would already work as long as you used explicit, uniform type casts:
demo at db<>fiddle