在 Oracle 中,我如何创建存储过程以在 2 个表中插入值

In Oracle, how do i create stored procedure to insert value in 2 tables

我试图在下面的两个 table 中插入详细信息。但它显示错误。我哪里错了?

create or replace PROCEDURE ADD_customer_order( 
customer_id in varchar, Shipping_id_arg in number,
order_date_arg in date, Total_price_arg in decimal,
inventory_id_arg in number, order_quantity_arg in number) 
AS
BEGIN
INSERT INTO customer_order (customer_id,Shipping_id,Order_date,total_price) VALUES(customer_id_arg,Shipping_id_arg,order_date_arg, total_price_arg); 
insert into order_details (inventory_id,order_quantity) values(scope_identity(),inventory_id_arg,order_quantity_arg); 
END;

如果你的格式很好,它会有所帮助。

create or replace procedure add_customer_order( 
  customer_id      in varchar2, shipping_id_arg in number,
  order_date_arg   in date    , total_price_arg in decimal,
  inventory_id_arg in number  , order_quantity_arg in number) 
as
begin
  insert into customer_order 
  (customer_id    , shipping_id    , order_date    , total_price) 
  values
  (customer_id_arg, shipping_id_arg, order_date_arg, total_price_arg); 

  insert into order_details 
  (                  inventory_id    , order_quantity) 
  values
  (scope_identity(), inventory_id_arg, order_quantity_arg); 
end;

这样做,您很容易注意到第二个 INSERT 无效,因为您将 3 个值插入 2 列:

  insert into order_details 
  (                  inventory_id    , order_quantity) 
  values
  (scope_identity(), inventory_id_arg, order_quantity_arg); 

要么删除 scope_identity()(它是什么?),要么将其他列添加到要插入的列列表中。


阅读您的评论后,returning 条款似乎可能有所帮助。请参阅以下示例(比您的简单一些;不想输入那么多)。触发器用于自增ORDER_ID列。在 CUSTOMER_ORDER table 中(我在 11g XE 上;这里没有标识列)。

SQL> create table customer_order (order_id number, customer_id number);

Table created.

SQL> create table order_details (order_id number, inventory_id number);

Table created.

SQL> create sequence seqo;

Sequence created.

SQL> create or replace trigger trg_co
  2    before insert on customer_order
  3    for each row
  4  begin
  5    :new.order_id := seqo.nextval;
  6  end;
  7  /

Trigger created.

过程:注意第 4 行中声明的局部变量和第 7 行中的 returning 子句:

SQL> create or replace procedure p_test
  2    (par_customer_id in number, par_inventory_id in number)
  3  is
  4    l_order_id   customer_order.order_id%type;
  5  begin
  6    insert into customer_order (customer_id) values (par_customer_id)
  7    returning order_id into l_order_id;
  8
  9    insert into order_details (order_id, inventory_id)
 10    values (l_order_id, par_inventory_id);
 11  end;
 12  /

Procedure created.

测试:

SQL> exec p_test(100, 200);

PL/SQL procedure successfully completed.

SQL> exec p_test (235, 2230);

PL/SQL procedure successfully completed.

SQL> select * From customer_order;

  ORDER_ID CUSTOMER_ID
---------- -----------
         1         100
         2         235

SQL> select * From order_details;

  ORDER_ID INVENTORY_ID
---------- ------------
         1          200
         2         2230

SQL>

两个 table 中使用相同的 ORDER_ID 值。