Select result into a type with array

Select result into a type with array

创建了这样的类型:

create type type_student as (student_id numeric, first_name text, subjects text[]);

我正在尝试创建一个可以收集学生的函数:

create function collect_students() returns setof type_student
as $function$
declare
   v_result type_student;
   v_student RECORD
begin
   for v_student in select id, first_name, (subject1, subject2, subject3) from students
   loop
      v_result := v_student;
      return next v_result;
   end loop;
end;
$function$ language plpgsql;

其中id, first_name, subject1, subject2, subject3 是students table.

中的列

我收到与 type_student 类型中的 subjects 值相关的转换错误。有没有办法在不单独分配数组的每个元素的情况下做到这一点?

subjects 声明为文本数组。您的 SELECT returns 记录类型列,而不是数组。

以下应该有效:

select id, first_name, array[subject1, subject2, subject3] from students

但是,您不需要类型,也不需要 FOR 循环,也不需要 PL/pgSQL:

create function collect_students() 
  returns table (student_id numeric, first_name text, subjects text[])
as $function$
  select id, first_name, array[subject1, subject2, subject3]
  from students
$function$ 
language sql;

如果您确实想使用 PL/pgSQL,您仍然不需要(慢速)FOR 循环。一个简单的 return query select ...; 就可以了。