0

I have a multitude of functions which insert different data into several tables. In some cases, for all functions, a staff ID column will need to be populated. Since all of the data inserting functions return the ID of the inserted row, I could do set_staff_id(staff_id, insert_data1(...)); Instead of adding an optional staff_id argument to all data inserting functions, and coppying the set staff_id code too.

I'm trying to avoid code duplication, but wonder if this is the correct aproach. Thanks.

1 Answer 1

1

Postgres allows you to use insert inside a CTE. So, this formulation might help:

with s as (
      insert into staff(. . .)
          values (. . .)
          returning *
     ),
     t1 as (
      insert into t1(staffid, . . . )
          select s.staffid, . . . 
          from s
     )
insert into t2(staffid, . . . )
    select s.staffid, . . . 
    from s;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, I haven't used CTEs at all before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.