2010-07-17 130 views
0

我正在嘗試創建一個觸發器來執行以下操作。CREATE觸發器幫助Oracle

在表A插入後,基於ID的查詢表B(TableA.id = TableB.id),並插入相應的信息到表A

我有一種感覺,我的路要走,到目前爲止所以任何幫助將不勝感激

CREATE OR REPLACE TRIGGER myTrig 
AFTER INSERT 
ON TABLEA 
BEGIN 
    INSERT INTO TABLEA 
    SELECT TABLEB.FIRST_NAME, TABLEB.LAST_NAME, SYSDATE 
    FROM TABLEA JOIN TABLEB ON 
    TABLEA.STUDENT_ID=TABLEB.STUDENT_ID 
    insert into TABLEA values (....); 
END; 

回答

2

這將無法正常工作。想想你在問什麼。你想要一個觸發器,當一行被插入到tableA中時觸發到將一行插入表A。觸發器什麼時候停止發射?

甲骨文是足夠聰明的一步,防止觸發節節攀升無窮:

SQL> create or replace trigger t69_after_ins 
    2  after insert on t69 
    3 begin 
    4  insert into t69 values ('blah', 'blah', 99); 
    5 end; 
    6/

Trigger created. 

SQL> 

這裏發生了什麼:

SQL> insert into t69 values ('this', 'that', 1)  
    2/

insert into t69 values ('this', 'that', 1) 
      * 
ERROR at line 1: 
ORA-00036: maximum number of recursive SQL levels (50) exceeded 
ORA-06512: at "APC.T69_AFTER_INS", line 2 
ORA-04088: error during execution of trigger 'APC.T69_AFTER_INS' 
ORA-06512: at "APC.T69_AFTER_INS", line 2 
ORA-04088: error during execution of trigger 'APC.T69_AFTER_INS' 
ORA-06512: at "APC.T69_AFTER_INS", line 2 
ORA-04088: error during execution of trigger 'APC.T69_AFTER_INS' 
ORA-06512: at "APC.T69_AFTER_INS", line 2 
ORA-04088: error during execution of trigger 'APC.T69_AFTER_INS' 
ORA-06512: at "APC.T69_AFTER_INS", line 2 
ORA-04088: error during execution of trigger 'APC.T69_AFTER_INS' 
ORA-06512: at "APC.T69_AFTER_INS", line 2 
ORA-04088: error during execution of trigger 'APC.T69_AFTER_INS' 
ORA-06512: at "APC.T69_AFTER_INS", line 2 
ORA-04088: error during execution of trigger 'APC.T69_AFTER_INS' 
ORA-06512: at "APC.T69_AFTER_INS", line 2 
ORA-04088: error during execution of trigger 'APC.T69_AFTER_INS' 
ORA-06512: at "APC.T69_AFTER_INS", line 2 
ORA-04088: error during execution of trigger 'APC.T69_AFTER_I 


SQL> 

「有什麼辦法,我可以更新 TableA根據來自TableB的信息給出 這兩個表中的ID?「

如果「更新」你實際上意味着UPDATE和 - 關鍵 - 取決於精確的邏輯,你希望實現,那麼也許是:

SQL> create or replace trigger t69_after_ins 
    2  after insert on t69 
    3 begin 
    4  update t69 
    5   set name = (select name from t23 
    6      where t23.id = t69.id) 
    7   where name is null; 
    8 end; 
    9/

Trigger created. 

SQL> insert into t69 (id, name) values (122, null) 
    2/

1 row created. 

SQL> select name from t69 
    2 where id = 122 
    3/

NAME 
---------- 
MAISIE 

SQL> 

然而,這仍然是一個壞主意。觸發器很難理解,並且可能會對我們的SQL性能產生有害的影響。所以我建議你嘗試找出一種將你的邏輯構建到應用程序主體中的方法,而不是嘗試使用觸發器。

+0

好吧,這是有道理的。有沒有什麼辦法可以根據來自TableB的信息更新TableA,給定兩個表中的ID? – relyt 2010-07-17 04:26:44