PostgreSQL函数返回多个结果集

fzwojiic  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(5)|浏览(240)

是否可以从Postgres函数返回多个结果集,如MSSQL:

CREATE PROCEDURE test

AS

SELECT * FROM first_table

SELECT * FROM second_table

字符集

dgtucam1

dgtucam11#

多查询返回单个结果集

自PostgreSQL 8.3**以来,有一种更简单的方法:

CREATE FUNCTION test()
  RETURNS SETOF first_table
  LANGUAGE plpgsql AS
$func$
BEGIN
   RETURN QUERY
   SELECT * FROM first_table;

   RETURN QUERY
   SELECT * FROM second_table;  -- same row type as first_table!
END
$func$;

字符集
电话:

SELECT * FROM test();


两个结果集都被追加到从函数返回的单个集合中。当然,行类型必须匹配。
参见RETURN QUERY的手册。

返回多个游标

你可以 * 返回多个游标,这不是一回事,确切地说,因为你必须依次从每个游标执行FETCH。而且你必须在同一个事务中完成所有这些。手册中有一个代码示例。从函数返回大行集可能很有用。在大多数情况下,我宁愿依次运行每个SELECT语句。

dfddblmv

dfddblmv2#

CREATE OR REPLACE FUNCTION "pr_GetCustomersAndOrders"()
RETURNS SETOF refcursor AS
$BODY$DECLARE
customerRC refcursor;
orderRC refcursor;
BEGIN
open customerRC FOR
SELECT * FROM customers;
RETURN NEXT customerRC;

open orderRC FOR
SELECT * FROM orders;
RETURN NEXT orderRC;
RETURN;
END;$BODY$
LANGUAGE 'plpgsql' VOLATILE;
ALTER FUNCTION "pr_GetCustomersAndOrders"() OWNER TO postgres;

字符集
I.o.w.使用refcursors:)

zysjyyx4

zysjyyx43#

CREATE OR REPLACE FUNCTION public.TestReturnMultipleTales
( 
 param_coid integer, 
 ref1 refcursor,
 ref2 refcursor
)
RETURNS SETOF refcursor 
LANGUAGE 'plpgsql'
COST 100
VOLATILE PARALLEL UNSAFE
ROWS 1000

AS $BODY$
DECLARE
            
BEGIN
  OPEN ref1 FOR SELECT * FROM dbo.tbl1 WHERE coid = param_coid;
  RETURN NEXT ref1;

  OPEN ref2 FOR SELECT * FROM dbo.tbl2 LIMIT 5;
  RETURN NEXT ref2;
END;
$BODY$;

USE IN pgSQL Query:- 

BEGIN;
    SELECT football_players.show_cities_multiple(123456, 'Ref1', 'Ref2');
    FETCH ALL IN "Ref1";
    FETCH ALL IN "Ref2";
COMMIT;

SELECT football_players.show_cities_multiple(123456, 'Ref1', 'Ref2');
FETCH ALL IN "Ref1";

SELECT football_players.show_cities_multiple(123456, 'Ref1', 'Ref2');
FETCH ALL IN "Ref2";

字符集

3pvhb19x

3pvhb19x4#

如果first_tablesecond_table具有相同的布局,您也可以只使用

SELECT * FROM first_table WHERE ...
UNION ALL
SELECT * FROM second_table WHERE ...

字符集

**[编辑:感谢一位评论者(他的名字可能不是“null”:))指出UNION ALLUNION快。

ufj5ltwl

ufj5ltwl5#

是的
范例:

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)

字符串
当然,您可以使用现有的数据表/检视或自订型别做为传回型别。
使用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

相关问题