Get ID of last inserted row and use it to insert into another table in a stored procedure

匆匆过客 提交于 2019-12-12 00:44:35

问题


I have the following stored procedure which we use to insert data into a table:

CREATE OR REPLACE PROCEDURE mySproc
(
 invoiceId IN NUMBER
 customerId IN NUMBER
)
IS
BEGIN 
    INSERT INTO myTable (INVOICE_ID) 
    VALUES (invoiceId);
END mySproc;
/

What I am trying to do is to get the last inserted ID (this is the primary key field on myTable and auto incremented using a sequence) and insert it into another table, I have tried the following but could not get it working:

CREATE OR REPLACE PROCEDURE mySproc
(
 invoiceId IN NUMBER
 customerId IN NUMBER
)
IS
BEGIN 
    INSERT INTO myTable (INVOICE_ID) 
    VALUES (invoiceId)

    returning id into v_id;

    INSERT INTO anotherTable (ID, customerID) 
    VALUES (v_id, customerId);  
END mySproc;
/

I am getting this error: [Error] PLS-00049 (59: 26): PLS-00049: bad bind variable 'V_ID' I think I need to declare v_id somewhere but I tried before and after the BEGIN statement but that gave another error.

Any ideas as to how to do this?

Thanks


回答1:


Change your procedure to

CREATE OR REPLACE PROCEDURE mySproc
(
 invoiceId IN NUMBER,  -- Added comma
 customerId IN NUMBER
)
IS
    v_id  NUMBER;  -- ADDED
BEGIN 
    INSERT INTO myTable (INVOICE_ID) 
    VALUES (invoiceId)
    returning id into v_id;

    INSERT INTO anotherTable (ID, customerID) 
    VALUES (v_id, customerId);  
END mySproc;

Share and enjoy.



来源:https://stackoverflow.com/questions/17968704/get-id-of-last-inserted-row-and-use-it-to-insert-into-another-table-in-a-stored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!