1

I have an old MSSQL procedure that needs to be ported to a PostgreSQL function. Basically the SQL procedure consist in a CURSOR over a select statement. For each cursor entity i have three select statements based on the current cursor output.

FETCH NEXT FROM @cursor INTO @entityId
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT * FROM table1 WHERE col1 = @entityId
SELECT * FROM table2 WHERE col2 = @entityId
SELECT * FROM table3 WHERE col3 = @entityId
END

The tables from the SELECT statements have different columns.

I know that the PostgreSQL use refcursor in order to return multiple result sets but the question is if is possible to open and return multiple dynamic refcursors inside of a loop?

The Npgsql .NET data provider is used for handling the results.

Postgres test code with only 1 cursor inside loop:

CREATE OR REPLACE FUNCTION "TestCursor"(refcursor) 
RETURNS SETOF refcursor AS
$BODY$

DECLARE
    entity_id integer;  
BEGIN

    FOR entity_id IN SELECT "FolderID" from "Folder"
    LOOP
        OPEN $1 FOR SELECT * FROM "FolderInfo" WHERE "FolderID" = entity_id;
        RETURN NEXT $1;
        CLOSE $1;   
    END LOOP;
END;

$BODY$
LANGUAGE 'plpgsql' VOLATILE;

Then the test code:

BEGIN;
SELECT * FROM "TestCursor"('c');
FETCH ALL IN c;
COMMIT;

The SELECT * FROM "TestCursor"('c'); output is like on screenshot:enter image description here Then when i try to fetch data i get the error: ERROR: cursor "c" does not exist

Trasnea Daniel
  • 307
  • 2
  • 12
  • PostgreSQL not supports stored procedures,So you can return only one result at a time. – Abhishek Ginani Nov 03 '15 at 09:00
  • 5
    Is possible. Check this [post](http://stackoverflow.com/questions/756689/postgresql-function-returning-multiple-result-sets). – Trasnea Daniel Nov 03 '15 at 09:09
  • Can you please elaborate what is selected from the 3 tables and how you want it returned? A `refcursor` is not a result set, for instance. If the columns of the three tables are identical in data type, you can `UNION` the queries into one and then return that result set. – Patrick Nov 03 '15 at 09:29
  • The tables have different columns so UNION cannot be used. – Trasnea Daniel Nov 03 '15 at 09:33
  • It is not duplicate. I saw this post before i post this question. The problem here is that the refcursors are open-close inside of a LOOP. When you execute this function you will get a list of cursors and I don't know how to fetch data from them. – Trasnea Daniel Nov 03 '15 at 10:01

1 Answers1

0

You can emulate it via SETOF refcursor. But it is not good idea. This T-SQL pattern is not supported well in Postgres, and should be prohibited when it is possible. PostgreSQL support functions - function can return scalar, vector or relation. That is all. Usually in 90% is possible to rewrite T-SQL procedures to clean PostgreSQL functions.

Pavel Stehule
  • 42,331
  • 5
  • 91
  • 94