Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

sql - Select result into a type with array

Having such type created:

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

I am trying to create a function that would collect the students:

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;

Where id, first_name, subject1, subject2, subject3 are columns in the students table.

I am getting casting errors connected with subjects value in the type_student type. Is there a way to do it without assigning each element of the array individually?

question from:https://stackoverflow.com/questions/65915706/select-result-into-a-type-with-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

subjects is declared as an array of text. Your SELECT returns a record type column, not an array.

The following should work:

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

However, you don't need a type, nor a FOR loop, nor PL/pgSQL for this:

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;

If you do want to use PL/pgSQL you still don't need a (slow) FOR loop. A simple return query select ...; will do.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...