Postgresql error: cannot open EXECUTE query as cursor

Postgresql error: cannot open EXECUTE query as cursor

我编写了一个函数来使用动态查询从下面的 table 中读取某些列:

CREATE OR REPLACE FUNCTION select_cols ()
    RETURNS SETOF mytable_name
    LANGUAGE plpgsql
    AS $$
DECLARE
    list_of_columns text;
BEGIN
    SELECT
        string_agg(trim(cols::text, '()'), ', ') INTO list_of_columns
    FROM (
        SELECT
            'mytable_name.' || column_name
        FROM
            information_schema.columns
        WHERE
            table_name = 'mytable_name'
            AND column_name LIKE 'rm%_b'
            OR column_name LIKE 'rm%_s') AS cols;
    RETURN query EXECUTE concat(format('select %s from mytable_name', list_of_columns), ' RETURNING *');
END
$$;

尽管当我运行

select * from select_cols();

它给我一个错误:“无法打开 EXECUTE 查询作为游标”。 如果有人可以帮助解决这个问题,我将不胜感激

您没有返回一个结果集,而是仅聚合了一个 table 的结果集。所以,只有一个 table 你可以使用:

CREATE OR REPLACE FUNCTION select_colsx ()
    RETURNS text
    LANGUAGE plpgsql
    AS $$
DECLARE
    list_of_columns text;
BEGIN
    SELECT
        'select '||string_agg(trim(cols::text, '()'), ', ') || ' from pg_class RETURNING *' 
        INTO list_of_columns
    FROM (
        SELECT
            'pg_class.' || column_name
        FROM
            information_schema.columns
        WHERE
            table_name = 'pg_class'
            AND column_name LIKE 'oid'
            OR column_name LIKE 'relacl') AS cols;
    RETURN  list_of_columns ;
END
$$;

select select_colsx();

DB Fiddle Example

RETURN QUERY EXECUTE 是在 PostgreSQL 8.4 中引入的。升级到不太古老的版本。