Postgresql stored procedure return select result set

断了今生、忘了曾经 提交于 2020-01-11 09:11:31

问题


In Microsoft SQL server I could do something like this :

create procedure my_procedure @argument1 int, @argument2 int
as
    select *
    from my_table
    where ID > @argument1 and ID < @argument2

And that would return me table with all columns from my_table.

Closest thing to that what I managed to do in postgresql is :

create or replace function
    get_test()
returns setof record
as
$$ select * from my_table $$
language sql

or i could define my table type, but manually recreating what technically already exists is very impractical.

create or replace function
    get_agent_summary()
returns table (
    column1 type, column2 type, ...
)
as
$$
begin
    return query select col1, col2, ... from my_existing_table;
...

and it is pain to maintain.

So, how can I easily return resultset without redefining defining every single column from table that I want to return?


回答1:


In Postgres a table automatically defines the corresponding type:

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);

The syntax is more verbose than in MS SQL Server because you can create functions in one of several languages and functions may be overloaded.



来源:https://stackoverflow.com/questions/41035386/postgresql-stored-procedure-return-select-result-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!