Dynamically define returning row types based on a passed given table in plpgsql?

佐手、 提交于 2019-12-07 18:31:27
Erwin Brandstetter

Is there a way to define result row return types based on a known table dynamically within the function?

If by "based on a known table" you mean "exactly like a known table", then yes.

SQL is a strictly typed language and functions must be created with a well defined return type. You can fall back to anonymous records like you obviously did (with RETURNS SETOF record), but then you are required to add a column definition list for every call, like the error message tells you. Something like:

SELECT *
FROM   my_function('foo') AS foo (
          colum_name1 integer  -- name and data type for every column
        , colum_name2 text
        , colum_name3 real);

And this is hardly dynamic.

Your question leaves room for interpretation, but "based on a known table" would indicate that a polymorphic function might do the trick. The return type can be based on any registered row type dynamically, and there is one for every table in the system automatically. Barebone code example:

CREATE OR REPLACE FUNCTION my_function(_rowtype anyelement)
  RETURNS SETOF anyelement AS
$func$
BEGIN
   RETURN QUERY EXECUTE format(
     'SELECT * FROM %s LIMIT 10'
    , pg_typeof(_rowtype)  -- pg_typeof() returns regtype, quoted where necessary
      );
END
$func$ LANGUAGE plpgsql;

Call:

SELECT * FROM my_function(NULL::my_table);

Detailed instructions in this related answer (look to the last chapter "Various complete table types"):

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