How to select all rows from refcursor returned by PL/pgSQL function?

跟風遠走 提交于 2019-12-06 02:46:22

问题


I have a function some_func() that returns refcursor:

CREATE OR REPLACE FUNCTION some_func() RETURNS refcursor AS (...)

I want to call this function from console and display the result set from the cursor returned by it. In Oracle I would write:

SELECT * FROM TABLE(some_func());

What is the equivalent of that construction on PosgreSQL?


回答1:


A refcursor is referred to by its name, either auto-generated or chosen by you. This page of the doc gives an example for each.

To fetch results from a refcursor you must have the cursor's name. In the case of generated names that'll be something like <unnamed portal 1>". You can then:

FETCH ALL FROM "<unnamed portal 1>";

The cursor name is returned from the function as the refcursor result, so you can get it from there.




回答2:


Lets say you have a postgres function written in such a way that return a refcursor;

CREATE OR REPLACE FUNCTION "com.mkindika"."myfunction" ("refcursor", other input  parameters) RETURNS "pg_catalog"."refcursor" AS 
$body$
DECLARE

---- query

END;
$body$
LANGUAGE 'plpgsql' STABLE CALLED ON NULL INPUT SECURITY INVOKER;

If you want to print the refcursor you may use following lines of code;

BEGIN;
SELECT "com.mkindika"."myfunction" ("refcursor",other input parameters);
FETCH ALL IN "refcursor";


来源:https://stackoverflow.com/questions/11135815/how-to-select-all-rows-from-refcursor-returned-by-pl-pgsql-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!