也许,您面临着不受控制的输入情况。您的程序需要自行控制它们。有两种处理错误的方法。
首先,您可以通过Exceptions处理错误。
CREATE OR REPLACE PROCEDURE InoviceEntry_step1
(X in number, Y in number)
AS
parent_not_found exception;
pragma exception_init(parent_not_found, -2291);
BEGIN
INSERT INTO INVOICE(inv_number, cus_code, inv_date, inv_subtotal, inv_tax, inv_total)
VALUES(X, Y, SYSDATE, 0, 0, 0);
COMMIT;
EXCEPTION
WHEN parent_not_found
THEN DBMS_OUTPUT.PUT_LINE('Error: CUSTOMER_ID = ' || Y || ' is not found.');
WHEN OTHERS
THEN DBMS_OUTPUT.PUT_LINE('Error');
END;
其次,您可以自己处理错误。例如,我在插入发票之前检查客户表中的“cus_code”。
CREATE OR REPLACE PROCEDURE InoviceEntry_step1
(X in number, Y in number)
AS
CURSOR c_customer IS (SELECT ID FROM CUSTOMER WHERE ID = Y AND ROWNUM =1);
v_ID NUMBER;
BEGIN
OPEN c_customer;
FETCH c_customer INTO v_ID;
IF c_customer%NOTFOUND
THEN
--Option1: If it shouldn't happend with your designed, you can just let error message without insert data.
DBMS_OUTPUT.PUT_LINE('Error: CUSTOMER_ID = ' || Y || ' is not found.');
DBMS_OUTPUT.PUT_LINE('Please create customer profile.');
--Option2: You may add customer_id first and insert invoice, if you want but I don't recommend.
INSERT INTO CUSTOMER (ID) VALUES(Y);
DBMS_OUTPUT.PUT_LINE('CUSTOMER_ID = ' || Y || ' has been created.');
INSERT INTO INVOICE(inv_number, cus_code, inv_date, inv_subtotal, inv_tax, inv_total)
VALUES(X, Y, SYSDATE, 0, 0, 0);
DBMS_OUTPUT.PUT_LINE('INVOICE_NO = ' || X || ' has been created.');
ELSE
INSERT INTO INVOICE(inv_number, cus_code, inv_date, inv_subtotal, inv_tax, inv_total)
VALUES(X, Y, SYSDATE, 0, 0, 0);
DBMS_OUTPUT.PUT_LINE('INVOICE_NO = ' || X || ' has been created.');
END IF;
CLOSE c_customer;
COMMIT;
END;
但是,不要忘记“提交”交易。