Question

I know that a cursor can encapsulate a query, but can it also point to a variable value or multiple ones?

For example:

declare
my cursor refcursor;
var_x varchar;
begin
        var_x := (select x from table where id = 7);
        open mycursor for select(var_x);
end;

Is this possible in PL/pgSQL?

Was it helpful?

Solution

Yes, it can be done:

CREATE OR REPLACE FUNCTION f_value_cursor(_curs refcursor, _id1 int, _id2 int)
  RETURNS TABLE (col1 int, col2 text) AS
$func$
DECLARE
    var_x text := (SELECT t.col2 FROM tbl t WHERE t.tbl_id = _id1);
BEGIN

OPEN _curs FOR SELECT var_x;

RETURN QUERY
SELECT t.col1, t.col2
FROM   tbl t
WHERE  t.tbl_id >= _id2;

END
$func$  LANGUAGE plpgsql;

A cursor is good for any query that returns rows - even if it returns a single constant like in the example.

Using an unbound cursor variable as parameter, you can pass a name for the cursor to the function.

I made the function return a table at the same time, since that seems to be what you are after in those last couple of questions.

As mentioned in my previous answer, it is essential that you fetch values from the cursor in the same transaction:

BEGIN;
SELECT * FROM f_value_cursor('mycursor', 1, 2);
FETCH ALL FROM mycursor;
ROLLBACK; -- or COMMIT

SQL Fiddle.

For the record: consider a temporary table instead, which lives for the duration of the session (per default), not just for the transaction. Tables are much more versatile. Cursors make more sense for huge result sets.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top