PostgreSQL: How to pass table/view name as a param

2019-03-06 00:46发布

问题:

For example: I have a VIEW called "view1" which contains 'name' and 'slno' columns, now i want it to be display using FUNCTION called "f1" as shown below:

--Function

create or replace function f1(viewname varchar) 
returns table (name varchar,slno integer) as
$body$
begin
     return query
     select * from viewname;
end;
$body$
language plpgsql;

回答1:

This is dynamic SQL, so you need EXECUTE.

RETURN QUERY EXECUTE format('SELECT * FROM %I', "name");

Separately, that's a weird thing to want to do.