For en dynamisk forespørgsel skal du bruge kommandoen 'execute'.
EXECUTE dynamic-query-string INTO target-variable...
Manualen til dette er her:http://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN
HTH