转换为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.
请帮我,我是PostgreSQL的新用户,在此先感谢!
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';
推荐答案
这是基本的PL / PgSQL。使用PL / PgSQL的 执行..使用
语句和 format
函数以及%I
格式说明符。
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';
只有在您可能传递的所有表名都返回兼容分区的结果类型时,此方法才起作用,否则必须返回 SETOF RECORD
,然后在函数调用中传递表布局,有关 RECORD
和 SETOF RECORD的讨论,请参见文档。
。
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
.
查看 RETURNS TABLE
作为表类型为n的另一种方便选择不兼容b ut仍然可以通过合适的 SELECT
列表返回兼容的子集。
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.
如果要进行表分区,您应该做到这一点,因为有关表分区的PostgreSQL文档建议,使用表继承和触发器。
If you're doing table partitioning, you should really do it as the PostgreSQL documentation on table partitioning advises, using table inheritance and triggers.
(详细说明将SQL Server存储过程转换为PostgreSQL存储过程)
这篇关于转换为PostgreSQL动态查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!