How to return a table by rowtype in PL/pgSQL

安稳与你 提交于 2020-02-25 01:28:06

问题


I am trying to implement a function that returns a table with the same structure as an input table in the parameter, using PL/pgSQL (PostgreSQL 9.3). Basically, I want to update a table, and return a copy of the updated table with plpgsql. I searched around SO and found several related questions (e.g. Return dynamic table with unknown columns from PL/pgSQL function and Table name as a PostgreSQL function parameter), which lead to the following minimal test example:

CREATE OR REPLACE FUNCTION change_val(_lookup_tbl regclass)
RETURNS _lookup_tbl%rowtype AS --problem line
$func$
BEGIN
    RETURN QUERY EXECUTE format('UPDATE %s SET val = 2 RETURNING * ; ', _lookup_tbl);
END
$func$ LANGUAGE plpgsql;

But I can't get past giving the correct return type for TABLE or SETOF RECORD in the problem line. According to this answer:

SQL demands to know the return type at call time

But I think the return type (which I intend to borrow from the input table type) is known. Can some one help explain if it is possible to fix the signature of the above PL/pgSQL function?

Note, I need to parametrize the input table and return the update of that table. Alternatives are welcome.


回答1:


What you have so far looks good. The missing ingredient: polymorphic types.

CREATE OR REPLACE FUNCTION change_val(_tbl_type anyelement)
  RETURNS SETOF anyelement AS -- problem solved
$func$
BEGIN
   RETURN QUERY EXECUTE format(
      'UPDATE %s SET val = 2 RETURNING *;'
     , pg_typeof(_tbl_type))
     );
END
$func$ LANGUAGE plpgsql;

Call (important):

SELECT * FROM change_val(NULL::some_tbl);

SQL Fiddle.

More details (last paragraph):

  • Refactor a PL/pgSQL function to return the output of various SELECT queries


来源:https://stackoverflow.com/questions/27649910/how-to-return-a-table-by-rowtype-in-pl-pgsql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!