Postgres Function to insert multiple records in two tables

后端 未结 2 1289
情深已故
情深已故 2021-02-10 00:31
create table public.orders (
    orderID serial PRIMARY KEY,
    orderdate timestamp NOT NULL
);

create table public.orderdetails (
    orderdetailID serial PRIMARY KEY         


        
2条回答
  •  抹茶落季
    2021-02-10 01:18

    You can use an array of tuples to pass multiple rows to the function. You need a custom type:

    create type order_input as (
        item text,
        quantity integer);
    

    Use array of this type for an argument of the function:

    create or replace function insert_into_orders(order_input[])
    returns void language plpgsql as $$
    declare 
        inserted_id integer;
    begin
        insert into public.orders(orderdate) 
        values (now()) 
        returning orderid into inserted_id;
    
        insert into public.orderdetails(orderid, item, quantity)
        select inserted_id, item, quantity
        from unnest($1);
    end $$;
    

    Usage:

    select insert_into_orders(
        array[
            ('Red Widget', 10), 
            ('Blue Widget', 5)
        ]::order_input[]
    );
    
    select * from orderdetails;
    
     orderdetailid | orderid |    item     | quantity 
    ---------------+---------+-------------+----------
                 1 |       1 | Red Widget  |       10
                 2 |       1 | Blue Widget |        5
    (2 rows)
    

提交回复
热议问题