here is my stored proc in PostgreSQL version 15:
CREATE OR REPLACE PROCEDURE customer_select(OUT customers REFCURSOR)
LANGUAGE plpgsql
AS $$
BEGIN
OPEN customers FOR
SELECT * FROM public.customers;
END;
$$;
and here I am trying to call the proc
CALL customer_select('customer_cursor');
FETCH ALL FROM customer_cursor;
But I am getting an error
ERROR: cursor "customer_cursor" does not exist
How do I get this to work? thanks
2
Answers
You’re pretty close, I think the main issue is that you’re using an
OUT
parameter rather than anINOUT
parameter.What you currently have returns something like:
Meaning you’d have to do
fetch all from "<unnamed portal 13>";
Eg: you aren’t assigning it a name and a auto-generated name is being assigned instead. You could find this from a catalog (
pg_cursors
) table, but it’s better to explicitly name it.If you change the parameter to be
customers INOUT REFCURSOR
then you get something like:Meaning you can do:
Because the cursor was not declared before attempting to fetch from it in your PostgreSQL stored method, the error
cursor 'customer_cursor' does not exist
appears. Explicitly declaring the cursor before using the stored method will help you fix this problem. The cursor can be declared and linked to the output of thecustomer_select
stored procedure using theDECLARE
command. Once the stored procedure has been called, the result will be linked to the declared cursor even if the cursor name is not specified. Finally, it is possible to retrieve data from the cursor without mentioning its name in theFETCH
statement. With this revised method, you may access the data as intended while also ensuring that the cursor is correctly specified and that the error is removed.