简体   繁体   English

转换为PostgreSQL动态查询

[英]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 ! 请帮我这个我是PostgreSQL的新手,在此先感谢!

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

This is basic PL/PgSQL. 这是基本的PL / PgSQL。 Use PL/PgSQL's EXECUTE .. USING statement and format function with the %I format-specifier. 使用PL / PgSQL的EXECUTE .. USING语句format函数与%I格式说明符。

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. 否则,您将必须返回SETOF RECORD ,然后在函数调用中传递表格布局。 See the documentation for a discussion of RECORD and SETOF RECORD . 有关RECORDSETOF 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. 查看RETURNS TABLE作为另一种方便的替代方法,当表类型不兼容但您仍然可以通过合适的SELECT列表返回兼容的子集。

If you're doing table partitioning, you should really do it as the PostgreSQL documentation on table partitioning advises , using table inheritance and triggers. 如果您正在进行表分区,那么您应该使用表继承和触发器, 就表分区的PostgreSQL文档提供建议

(Elaborating on Convert SQL Server stored procedure into PostgreSQL stored procedure ) (详细说明将SQL Server存储过程转换为PostgreSQL存储过程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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