Postgresql return 来自 Table 的 SETOF 行

Postgresql return SETOF row from Table

我在 DBMS (Postgresql) 中有这个存储过程

CREATE OR REPLACE FUNCTION getallentree()
  RETURNS SETOF entree AS
$BODY$
begin 
   select * from entree ; 
end;
$BODY$
  LANGUAGE plpgsql 

调用此过程后:

select *  from getAllEntree(); 

我收到此错误:

ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT:  PL/pgSQL function getallentree() line 3 at SQL statement

********** Error **********

ERROR: query has no destination for result data
SQL state: 42601
Hint: If you want to discard the results of a SELECT, use PERFORM instead.
Context: PL/pgSQL function getallentree() line 3 at SQL statement

您只需将 return query 添加到您的 select 语句中:

CREATE OR REPLACE FUNCTION getallentree()
  RETURNS SETOF entree AS
$BODY$
begin 
   return query
   select * from entree ; 
end;
$BODY$
  LANGUAGE plpgsql 

对于这样一个简单的查询,最好使用SQL函数。与 PL/pgSQL 函数相比,它们可以被查询优化器内联和更好地优化:

CREATE OR REPLACE FUNCTION getallentree()
  RETURNS SETOF entree AS
$BODY$
   select * from entree ; 
$BODY$
  LANGUAGE sql;

如果您确实需要 PL/pgSQL 进行一些您没有向我们展示的其他处理,那么 Mureinik 关于使用 return query 的回答是正确的选择。