6
I am developing a function in Postgres that aims to recover for each record of a query the result value of a check contained in a set of functions. Of these functions only one will return the correct value. These functions have a common prefix 'fn_condition_' and receive as a parameter an object of type 'my_table'.
As the number of functions that make the check not known, I decided to consult the catalog of Postgres, from the table pg.catalog.pg_proc searching for functions with the prefix 'fn_condition_' and execute them dynamically from the command EXECUTE.
My difficulty is in how to pass the parameter correctly to the EXECUTE command.
How to indicate in the excerpt commented on the function below 'select ' || funcoes.proname || '(' || registro || ')';
that the input is of type my_table?
create or replace function testa_condicoes()
returns void as
$$
declare
registro minha_table%rowtype;
funcoes pg_proc%rowtype;
begin
set search_path = 'pg_catalog';
for registro in (select * from minha_table where id in (1,2,3)) loop
for funcoes in (
SELECT p.proname
FROM pg_namespace n
JOIN pg_proc p
ON p.pronamespace = n.oid
WHERE n.nspname = 'operacional'
and p.proname like ('fn_condicao_%')
order by p.proname)
loop
--execute 'select ' || funcoes.proname || '(' || registro || ')';
end loop;
end loop;
end;
$$
language plpgsql;
Role model
create or replace function fn_condicao_1(registro minha_table)
returns bigint as
$$
begin
if (registro.atributo1 > registro.atributo2) then
return 1;
end if;
return null;
end;
$$
language plpgsql;
Hello, Clodoaldo. I tested your solution. It presents the same result as the one already reached by me, an error in the execution of the query: ERROR: syntax error in or next to "," at Character 37. QUERY:
select fn_condicao_1((6566,14,9999,,,,,,,,,,,,,,,,,,,0,A,"2016-01-14 11:18:59.140774",1,,,,,,,,,0,))
– Geison Santos
@Geison: I updated the answer by putting the cast to
::my_table
. No 9.5 worked without the cast but maybe your version does not make the automatic cast– Clodoaldo Neto
It displays the same error message as the previous comment. The difference is in the cast included:
::my_table
– Geison Santos
@Geison: How it is returning a string instead of
my_table
so I put areplace
and kept the cast:– Clodoaldo Neto