Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a select from a plpgsql function

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.

like image 528
justanother1 Avatar asked Dec 27 '22 00:12

justanother1


1 Answers

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, ...);
like image 152
Eelke Avatar answered Jan 10 '23 19:01

Eelke