I need to return a dynamically generated select statement from a plpgsql function. This is what I have so far:
CREATE OR REPLACE FUNCTION qa_scf(cname character varying, tname character varying)
RETURNS text AS
$BODY$
BEGIN
return '* from ' ||tname|| 'where ' ||cname ||' != ''AL''';
end;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
The caller, ran from a batch file:
select qa_scf('state', 'testtable')
This returns the literal text "qa_scf * from testtable where state != 'AL'". I need to run this query from an sql batch file, but I cannot seem to find the right return statement to have this function return a string and then have the sql batch execute it. I'm using Postgres 9.0.
The return type should be SETOF RECORD. Executing and returning the SQL would become RETURN QUERY EXECUTE. Your query is missing SELECT. There was also whitespace missing before the where.
CREATE OR REPLACE FUNCTION qa_scf(cname character varying, tname character varying)
RETURNS SETOF RECORD AS
$BODY$
BEGIN
RETURN QUERY EXECUTE 'SELECT * from ' ||tname|| ' where ' ||cname ||' != ''AL''';
END;
$BODY$
LANGUAGE plpgsql;
Calling this function will get a little complicated as you will have to specify the columns you expect in the result. Goes like this:
SELECT *
FROM qa_scf('foo', 'bar') AS t(col1_name col1_type, ...);
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