Search code examples
sqlpostgresqlviewcursorplpgsql

Fetch cursor from multiple tables view PostgreSQL


I try until couple of hours to fetch all the row from a view, created from multiple tables.

I have two tables (Position, and Vector) to which correspond respectively two custom composite types , type_position and type_vector

Position (id, sys_time, lat, lon)

Vector (id, sys_time, speed)

I want to create a temporary VIEW in plpgsql procedure to bring together all Position and Vector and order them by sys_time so i wrote :

CREATE TEMP VIEW posAndVectView AS
                    SELECT * from position
                    UNION ALL
                    SELECT * from vector;

I need to iterate over this view and made some work depends on Position and Vector attributes.

So i think i should use a cursor :

DECLARE 
 manyRows refcursor;
BEGIN

OPEN manyRows FOR 
SELECT * FROM posAndVectView ORDER BY sys_time ASC;
LOOP
FETCH manyRows INTO posOrVect;
EXIT WHEN NOT FOUND;
...
END LOOP;
CLOSE manyRows; 

So my question is what should the type of the posOrVect variable be in the DECLARE section ?

It seems to be sometimes a type_vector, sometimes a type_position...


Solution

  • I found the answer it is pretty simple. I need to declare the posOrVect variable with the record type as its mentionned in the PostgreSQL documentation :

    Record variables are similar to row-type variables, but they have no predefined structure. They take on the actual row structure of the row they are assigned during a SELECT or FOR command. The substructure of a record variable can change each time it is assigned to. A consequence of this is that until a record variable is first assigned to, it has no substructure, and any attempt to access a field in it will draw a run-time error.