简体   繁体   中英

Convert into PostgreSQL Dynamic Query

Below is one function which has one query ,

Now I want to convert into dynamic query. I want one table name parameter so query return data from multiple tables.

please help me in this I am new in PostgreSQL , Thanks in Advance !

create or replace function GetEmployees() 
returns setof weather as 
'select * from weather;' 
language 'sql';

This is basic PL/PgSQL. Use PL/PgSQL's EXECUTE .. USING statement and format function with the %I format-specifier.

create or replace function get_sometable(tablename regclass) 
returns setof whatever_type as 
BEGIN
RETURN QUERY EXECUTE format('select * from %I";', tablename);
END;
language 'plpgsql';

This will only work if all tablenames you might pass return compatible result types, as occurs with partitioning. Otherwise you'll have to return SETOF RECORD and then pass the table layout in the function invocation. See the documentation for a discussion of RECORD and SETOF RECORD .

Look into RETURNS TABLE as another convenient alternative for when the table types aren't compatible but you can still return a compatible subset via a suitable SELECT list.

If you're doing table partitioning, you should really do it as the PostgreSQL documentation on table partitioning advises , using table inheritance and triggers.

(Elaborating on Convert SQL Server stored procedure into PostgreSQL stored procedure )

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