Postgres Function to insert multiple records in two tables

后端 未结 2 1288
情深已故
情深已故 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:07

    Thanks Klin. That helped a lot.

    Further, I was able to avoid the usage of an explicit type and just having used the table defined as an array.

    Code below:

    -- Create table whose type will be passed as input parameter
    create table tbl_card
    (id integer,
    name varchar(10),
    cardno bigint)
    
    -- Create function to accept an array of table
    create or replace function fn_insert_card_arr (tbl_card[]) returns integer as $$
    begin
    insert into tbl_card (id, name,cardno)
    select id, name, cardno
    from unnest($1);
    
    return 0;
    end;
    $$ LANGUAGE plpgsql;
    
    -- Execute function by passing an array of table (type casted to array of type table)
    select fn_insert_card_arr(
    array[
        (1,'one', 2222777744448888), 
        (2,'two', 8888444466662222),
        (3,'three', 2222777744448888), 
        (4,'four', 8888444466662222)
    ]::tbl_card[]
    );
    

提交回复
热议问题