从多个表视图 PostgreSQL 中获取游标

Fetch cursor from multiple tables view PostgreSQL

我尝试了几个小时才从多个表创建的视图中获取所有行。

我有两个表(Position 和 Vector)分别对应两个自定义复合类型,type_positiontype_vector

位置 (id, sys_time, lat, lon)

矢量(id,sys_time,速度)

我想在 plpgsql 过程中创建一个临时 VIEW 以将所有 Position 和 Vector 放在一起并按 sys_time 排序,所以我写道:

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

我需要迭代此视图并根据 Position 和 Vector 属性进行一些工作。

所以我想我应该使用游标:

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; 

所以我的问题是 DECLARE 部分中 posOrVect 变量的类型应该是什么?

好像有时候是type_vector,有时候是type_position...

简单。类型应该是 posAndVectView.

与任何其他 table 一样,还有一个与临时 table 同名的复合类型。

但是你需要看风景吗?您可以使用 UNION 打开查询的游标。在这种情况下,您将使用类型 position 因为它是第一个 table.

我发现答案很简单。 我需要使用 record 类型声明 posOrVect 变量,正如它在 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.