PostgreSQL存储过程返回查询结果集

9
在 Microsoft SQL Server 中,我可以做类似这样的事情:
create procedure my_procedure @argument1 int, @argument2 int
as
    select *
    from my_table
    where ID > @argument1 and ID < @argument2

这段话的意思是:返回一个包含“my_table”所有列的表格。在PostgreSQL中,最接近这个功能的语句是:
create or replace function
    get_test()
returns setof record
as
$$ select * from my_table $$
language sql

或者我可以定义我的表类型,但手动重新创建已经存在的东西在技术上非常不切实际。
create or replace function
    get_agent_summary()
returns table (
    column1 type, column2 type, ...
)
as
$$
begin
    return query select col1, col2, ... from my_existing_table;
...

“而且维护起来很麻烦。那么,我怎样才能轻松地返回结果集,而不必重新定义我想要返回的每一列?”

1
问题是什么? - Vao Tsun
@VaoTsun 如何在PostgreSQL中实现Microsoft SQL的某个功能? - Reygoch
1个回答

17
在Postgres中,表会自动定义相应的类型:
create or replace function select_my_table(argument1 int, argument2 int)
returns setof my_table language sql as $$
    select *
    from my_table
    where id > argument1 and id < argument2;
$$;

select * from select_my_table(0, 2);

由于可以使用多种语言创建函数,函数可以被重载,因此语法比MS SQL Server更冗长。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接