Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql stored procedure return select result set

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?

like image 740
Reygoch Avatar asked Dec 08 '16 08:12

Reygoch


People also ask

Can PostgreSQL stored procedure return resultset?

Both stored procedures and user-defined functions are created with CREATE FUNCTION statement in PostgreSQL. To return one or more result sets (cursors in terms of PostgreSQL), you have to use refcursor return type.

Can a stored procedure return a result set?

In addition to returning output parameters, a stored procedure can return a result set (that is, a result table associated with a cursor opened in the stored procedure) to the application that issues the CALL statement. The application can then issue fetch requests to read the rows of the result set cursor.

How do I return a selected query in PostgreSQL?

To return a table from the function, you use RETURNS TABLE syntax and specify the columns of the table. Each column is separated by a comma (, ). In the function, we return a query that is a result of a SELECT statement.

What is Refcursor in PostgreSQL?

PostgreSQL provides you with a special type called REFCURSOR to declare a cursor variable.


1 Answers

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.

like image 164
klin Avatar answered Nov 15 '22 10:11

klin