使用存储过程 PostgreSQL 11.1 从表中检索数据

MAK*_*MAK 0 postgresql postgresql-11

我的表格有两列colacolb.

我想使用存储过程从表中选择列。

注意:由于返回类型,我不想使用函数。

尝试:

CREATE OR REPLACE PROCEDURE public.sptest()
LANGUAGE sql

AS $BODY$
         select cola from test;
$BODY$;
Run Code Online (Sandbox Code Playgroud)

调用程序:

call sptest()
Run Code Online (Sandbox Code Playgroud)

输出:

数据输出中没有任何内容。

消息窗口显示:

CALL

Query returned successfully in 147 msec. 
Run Code Online (Sandbox Code Playgroud)

a_h*_*ame 5

您需要将 refcursor 定义为 inout 参数才能执行此操作:

CREATE OR REPLACE PROCEDURE public.sptest(result_data inout refcursor)
LANGUAGE plpgsql
AS $BODY$
begin
  open result_data for select cola from test;
end;
$BODY$;
Run Code Online (Sandbox Code Playgroud)

然后像这样调用它:

call sptest('data');
Run Code Online (Sandbox Code Playgroud)

传递的参数是返回的 refcursor 的名称。

是否显示结果取决于您使用的 SQL 客户端。

psql你需要做这样的事情:

begin; -- not required if you turned off autocommit
call sptest('data');
fetch all in "data";
commit;
Run Code Online (Sandbox Code Playgroud)

某些 SQL 客户端会自动为您执行此操作。