如何在PostgreSQL中返回表记录数组

问题描述

当尝试返回类型为table1的元素数组时,我收到类型不匹配错误,这是我声明的table1的固有类型。

Error occurred during sql query execution

Razón:
 sql Error [42P13]: ERROR: return type mismatch in function declared to return table1[]
  Detail: Actual return type is record[].
  Where: sql function "arrayof_records"

这是一个过于简化的代码,再现了我的问题。

drop table if exists table1 cascade;

create table table1 (
  id        serial primary key,title     text,create_dt timestamp default Now()
);

insert into table1 (title) values 
('one'),('two'),('three');

create or replace function arrayof_records ()
returns table1[]
stable language sql as $$
  select array_agg (t.*)
  from (
    select * from table1
    order by create_dt desc
  ) as t;
$$;

很明显,解析器在array_agg函数中期望其他表达式。我已经尝试过tt.**。他们都失败了。

我希望有一种语法,因为Postgresql 12文档指出“ array_agg(expression)|任何非数组类型”。

有什么主意吗?

解决方法

您可以使用稍微不同的方式创建数组:

create or replace function arrayof_records ()
  returns table1[]
  stable language sql 
as 
$$
  select array(
    select table1 
    from table1
    order by create_dt desc
  );
$$;

这通常也比array_agg()快。