PostgreSQL function returning multiple result sets

前端 未结 4 876
借酒劲吻你
借酒劲吻你 2020-11-27 19:08

Is it possible to return multiple result sets from a Postgres function, like in MSSQL:

CREATE PROCEDURE test

AS

SELECT * FROM first_table

SELECT * FROM se         


        
4条回答
  •  没有蜡笔的小新
    2020-11-27 19:50

    Yes.

    Example:

    test=# create function x () returns setof integer language plpgsql as $$ begin return next 1; return next 2; end $$;
    CREATE FUNCTION
    test=# select * from x();
     x 
    ---
     1
     2
    (2 rows)
    

    You can of course use an existing table/view or a custom type for the returned type.

    Example using language SQL:

    test=# create table customer (name varchar, birth_date date);
    CREATE TABLE
    test=# create function y () returns setof customer language sql as $$ 
    select * from customer
    union all
    select * from customer
    $$;
    CREATE FUNCTION
    test=# insert into customer values ('joe', now()::date);
    INSERT 0 1
    test=# insert into customer values ('jill', now()::date);
    INSERT 0 1
    test=# select * from y();
     name | birth_date 
    ------+------------
     joe  | 2009-04-16
     jill | 2009-04-16
     joe  | 2009-04-16
     jill | 2009-04-16
    (4 rows)
    

    See here for doc

提交回复
热议问题