我有一个问题,我正在尝试解决一个触发器,该触发器必须检查对象是否保存在表中。但是,如果我选择的元素与要插入的鳕鱼对象相同,则选择此对象表中不存在触发器将使我获得异常,但找不到数据。.如果触发器使我没有获得数据,我该怎么办?
我可以这样做吗?
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO VALUES TABLE_X (:NEW.A,:NEW.B,:NEW.C)
答案 0 :(得分:0)
是的,你可以做。
请考虑以下内容:
SQL> CREATE TABLE TABLE_X(A INT, B INT, C INT);
Table created
SQL> CREATE TABLE TABLE_Y(A INT, B INT, C INT);
Table created
SQL> CREATE OR REPLACE TRIGGER trg_bi_ins_y
2 BEFORE INSERT ON TABLE_Y
3 FOR EACH ROW
4 DECLARE
5 V_A TABLE_Y.A%TYPE;
6 BEGIN
7 BEGIN
8 SELECT Y.A
9 INTO V_A
10 FROM TABLE_Y Y
11 WHERE Y.A = :NEW.A;
12 EXCEPTION
13 WHEN NO_DATA_FOUND THEN
14 INSERT INTO TABLE_X VALUES(:NEW.A,:NEW.B,:NEW.C);
15 END;
16 END;
17 /
Trigger created
SQL> INSERT INTO TABLE_Y VALUES(1,0,0);
1 row inserted
SQL> SELECT * FROM TABLE_Y;
A B C
--- --- ---
1 0 0
SQL> SELECT * FROM TABLE_X;
A B C
--- --- ---
1 0 0
-- the row with value 1 for column A does not exist, and insertion to TABLE_X occurs.
SQL> INSERT INTO TABLE_Y VALUES(1,1,1);
1 row inserted
SQL> SELECT * FROM TABLE_Y;
A B C
--- --- ---
1 0 0
1 1 1
SQL> SELECT * FROM TABLE_X;
A B C
--- --- ---
1 0 0
-- the row with value 1 for column A already exists, and no insertion occurs.