Is it possible to define a function that takes a parameter of a generic type in Postgresql? So for example if I wanted to define a function where the argument could be either numeric or character varying:
CREATE OR REPLACE FUNCTION toStr(col ??Generic Type??)
RETURNS character varying AS
$BODY$
select
case when pg_typeof(col) = 'character varying'::regtype then col::'character varying'
case when pg_typeof(col) = 'numeric'::regtype then to_char(col::numeric, '999')
else 'Unsupported type'
$BODY$
So if this is possible what would my ??Generic Type?? be?
You can use the anyelement
pseudo type which accepts any data type;
CREATE OR REPLACE FUNCTION toStr(col anyelement)
RETURNS character varying
AS $$
select
case when pg_typeof(col) = 'character varying'::regtype then (col::character varying)
when pg_typeof(col) = 'numeric'::regtype then to_char(col::numeric, '999')
else 'Unsupported type' end
$$
LANGUAGE sql;
An SQLfiddle showing it in action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With