【问题标题】:Select result into a type with array将结果选择为带有数组的类型
【发布时间】:2021-01-27 08:51:45
【问题描述】:

创建了这样的类型:

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 是学生表中的列。

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

【问题讨论】:

    标签: sql postgresql plpgsql


    【解决方案1】:

    subjects 被声明为一个文本数组。您的 SELECT 返回记录类型列,而不是数组。

    以下应该有效:

    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 ...; 就可以了。

    【讨论】:

      猜你喜欢
      • 2015-02-09
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 2022-10-08
      • 1970-01-01
      • 2019-05-22
      • 2021-04-29
      • 2021-09-24
      相关资源
      最近更新 更多