【问题标题】:Postgresql - Stored Procedure that returns a table result setPostgresql - 返回表结果集的存储过程
【发布时间】:2021-11-07 16:57:43
【问题描述】:

我是 PostgreSQL v.13 的新手,想创建一个存储过程,它将接收一个整数值,然后从表中返回结果。

我有这个:

create or replace procedure public.sp_message_template_get(
   templateid int
)  language plpgsql AS $$
   
      
begin
    -- subtracting the amount from the sender's account 
 select * from public.message_template;

    --commit;
end;
$$ 

然后我尝试使用以下方法调用它:

call public.sp_message_template_get(1);

我收到以下错误:

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 sp_message_template_get(integer) line 6 at SQL statement
SQL state: 42601

有什么线索吗?

谢谢

【问题讨论】:

  • 存储过程不能返回东西。如果你想这样做,请使用一个函数。见Returning43.6.1.2。返回下一个并返回查询。仅供参考,您收到错误消息是因为您运行了 SELECT 并且没有捕获结果。为此,您需要使用PERFORM 43.5.2。执行 SQL 命令
  • 我很困惑,因为在 MS SQL Server 中您通常使用 SP 来返回值,所以在 PostgreSQL 中您必须使用函数来代替?那么SP的目的是什么?
  • @VAAA 好吧,Postgres 与 SQL Server 不同,在 Postgres 中,如果要返回某些内容,则需要使用函数。你需要migrate your mindset too
  • Procedures。过程的主要好处是您可以在其中进行事务管理。对于大多数事情,您可能想要使用函数。

标签: postgresql


【解决方案1】:

创建一个 sql 函数。

create or replace function message_template_get(templateid integer)
returns setof message_template language sql as
$$
  -- subtracting the amount from the sender's account (sql query)
  select * from public.message_template;
$$;

如果有理由使用 plpgsql 语言,请使用return query

create or replace function message_template_get(templateid integer)
returns setof message_template language plpgsql as
$$
begin
  -- subtracting the amount from the sender's account
  return query select * from public.message_template;
  -- maybe other statements here
end;
$$;

请注意,commit 在函数体中不是必需且非法的。可以使用多个 return queryreturn next 语句。

【讨论】:

    猜你喜欢
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    相关资源
    最近更新 更多