【问题标题】:Postgres Function to insert multiple records in two tablesPostgres函数在两个表中插入多条记录
【发布时间】:2017-01-29 00:15:29
【问题描述】:
create table public.orders (
    orderID serial PRIMARY KEY,
    orderdate timestamp NOT NULL
);

create table public.orderdetails (
    orderdetailID serial PRIMARY KEY,
    orderID integer REFERENCES public.orders(orderID),
    item varchar(20) NOT NULL,
    quantity INTEGER NOT NULL
);

我有上面的(非常简化的示例)表格,我想在一个操作中插入订单的详细信息和订单详细信息。

我熟悉事务,可以使用如下 SQL 命令插入数据:

DO $$
  DECLARE inserted_id integer;
  BEGIN
    INSERT INTO public.orders(orderdate) VALUES (NOW()) RETURNING orderID INTO inserted_id;

    INSERT INTO public.orderdetails(orderID, item, quantity)
    VALUES (inserted_id, 'Red Widget', 10),
           (inserted_id, 'Blue Widget', 5);
  END
$$ LANGUAGE plpgsql;

但是,如果可能的话,理想情况下,我希望有一个类似上述函数的查询,而不是存储在我的应用程序中。

谁能指出我向 postgres 函数提供多条记录的正确方向?或者,如果我想做的事情被认为是不好的做法,请让我知道我应该遵循什么其他路线。

提前致谢。

【问题讨论】:

  • 我真的不明白有这种关系的意义,为什么需要orderdetails 表?我会用一张桌子,交易没有问题
  • 您好 ad4s,这是一个简化的示例,orders 表将包含诸如订单日期、发货日期、发货地址等内容,而 orderdetails 表将按订单项进行细分。

标签: sql database postgresql plpgsql postgresql-9.4


【解决方案1】:

您可以使用元组数组将多行传递给函数。你需要一个自定义类型:

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

使用这种类型的数组作为函数的参数:

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 $$;

用法:

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)

【讨论】:

  • 由于javascript没有元组的概念,是否有一种直接的方法可以在pg-promise中执行这个函数?
【解决方案2】:

谢谢克林。这帮助很大。

此外,我能够避免使用显式类型,而只使用定义为数组的表。

代码如下:

-- 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[]
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 2023-04-04
    • 2017-12-11
    • 2019-12-16
    • 1970-01-01
    • 2018-05-07
    • 2020-10-18
    相关资源
    最近更新 更多