简体   繁体   中英

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.

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, ...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM