Getting results from a dynamic query in PL/pgSQL - Mailing list pgsql-general

From johann.uhrmann@xpecto.com (Johann Uhrmann)
Subject Getting results from a dynamic query in PL/pgSQL
Date
Msg-id 8aa974a1.0301270701.1af7693a@posting.google.com
Whole thread Raw
Responses Re: Getting results from a dynamic query in PL/pgSQL
List pgsql-general
Hello,

is there a possibility to retrieve results from a dynamically generated
query in PL/pgSQL?

That would be like this:

create function foo(text) returns text as '
DECLARE
   colname ALIAS FOR $1;
   result text;
BEGIN
   SELECT INTO result colname from my_table;
   RETURN result;
END;
' language 'plpgsql';


The actual column that is to be read from my_table should be passed as
argument to the function.
The example does not read the variable colname but tries to read a
column named "colname" from my_table which is not how it should work.

The keyword "EXECUTE" which could execute dynamic queries cannot return any
value that a select statement would. (At least there is nothing about that
in the docs.)


In order to write a trigger function that reads column names out of a table
and uses those column names afterwards, I need such a functionality.

I tried a workaround by using EXECUTE to create a function that reads
only the columns I need and then calling this dynamically generated function.
However, that works only one time - then I get the following message:

ERROR:  plpgsql: cache lookup for proc 52118 failed

plpgsql seems to cache the dynamically generated function even after it gets
dropped or overwritten with "create or replace function...".


Does anyone know how to use column names stored in variables within PL/pgSQL?



Thank You in advance,


Johann Uhrmann

pgsql-general by date:

Previous
From: Ryan VanderBijl
Date:
Subject: Re: serialization errors
Next
From: Charles Tassell
Date:
Subject: Re: stopping access to a database