https://supabase.com/ logo
Hey ya'll. I'm pretty new to writing sql and plpg...
# help
t
Hey ya'll. I'm pretty new to writing sql and plpgsql stuff so hopefully this is an easy fix that I just don't know yet. So I'm making an sql snippet that adds a student to the
students
table and then the function also gets an array of phone numbers and I need to add them to the
phones
table with the
new student_id
. I have gotten far enough that it add the student and returns the id then puts the id in a variable. The part I'm stuck on is the syntax for taking this array of phone numbers and and adding a row for each number along with the
student_id
. Heres what I have so far
Copy code
create or replace function insert_student(
  first_name text,
  last_name text,
  grade text,
  dob date,
  phones phone_type[]
)
RETURNS setof students
AS $$
declare
  student_id int8;
  begin
    INSERT INTO students
    (first_name, last_name, grade, dob) values (first_name, last_name, grade, dob)
    returning id INTO student_id;

    INSERT INTO phones
    (phone_number, student_id) values
     (phones, student_id); --THIS IS THE PART I'M STUCK ON

    RETURN query select * from students where students.id = student_id;
  end;
$$ language plpgsql;
n
Hello @Tater Of Tots! This thread has been automatically created from your message in #843999948717555735 a few seconds ago. We have already mentioned the @User so that they can see your message and help you as soon as possible! Want to unsubscribe from this thread? Right-click the thread in Discord (or use the ``...`` menu) and select "Leave Thread" to unsubscribe from future updates. Want to change the title? Use the ``/title`` command! We have solved your problem? Click the button below to archive it.
t
oh and I created a type of
phone_type
with this line
create type phone_type as (phone_number text);
s
First issue I'm seeing is you are using the variable name
student_id
which is also a column name. You need to change the variable name to something else.
t
huh. So it would seem.
I'll fix that
Copy code
create or replace function insert_student(
  first_name text,
  last_name text,
  grade text,
  dob date,
  phones phone_type[]
)
RETURNS setof students
AS $$
declare
  student_id_var int8;
  begin
    INSERT INTO students
    (first_name, last_name, grade, dob) values (first_name, last_name, grade, dob)
    returning id INTO student_id_var;

    INSERT INTO phones
    (phone_number, student_id) values
     (phones, student_id_var); --THIS IS THE PART I'M STUCK ON

    RETURN query select * from students where students.id = student_id_var;
  end;
$$ language plpgsql;
that ought to do it