2014-11-24 53 views
1

我有兩個表。表A像創建一個處理兩個表的觸發器

Name color 
a1  red 
a2  yellow 
a3  black 
a4  blue 

表B就像

Name minutes action 
b1  10   jump 
b2  20   run 
b3  40   dance 

我創建一個觸發器表B中插入行,如果動作是B.存在然後我打印新添加的信息。另外,如果新加入的人的顏色是紅色,我會算表B中有更多/更少分鐘多少人的代碼是一樣

create or replace trigger TR_insert_count 
Before INSERT On B 
For each row 

DECLARE 
l_act integer; 
l_less integer; 
l_more integer; 
l_equal integer; 

Begin 

select count(1) into l_act 
From B 
Where Action=:new.Action; 

select count(*) 
into l_less 
From B 
Where Action=:new.Action and MINUTES > :new.minutes; 

select count(*) 
into l_more 
From B 
Where Action=:new.Action and MINUTES < :new.minutes; 

select count(*) 
into l_equal 
From B 
Where Action=:new.Action and MINUTES = :new.minutes; 

if(l_act>0) then 
DBMS_OUTPUT.PUT_LINE ('There is duplicate.'); 
DBMS_OUTPUT.PUT_LINE ('The new input info is with name ' || :new.Name || ' with 
activity ' || :new.action ||' for ' ||:new.minutes || ' minutes.'); 

    if(:new.name in (select Name From A where color='red')) then 
    DBMS_OUTPUT.PUT_LINE('There are '||l_more ||'people having more minutes.'); 
    DBMS_OUTPUT.PUT_LINE('There are '||l_less ||'people having less minutes.'); 
    DBMS_OUTPUT.PUT_LINE('There are '||l_equal ||'people having the same minutes.'); 
    end if; 

end if; 
end 

它被編譯,但插排時,報告錯誤說觸發無效。我想知道是因爲我在這裏有行級別或表級觸發器,請問該怎麼辦?

回答

1

檢查警告你的編譯後觸發,它會給你一個確切的原因,它不能被編譯。但是,當您修復編譯錯誤[s]時,在插入到B期間,您將遇到 「ORA-04091:表XXXX正在變異...」:您無法在行級觸發器內發出對目標表的查詢,除非它使用自主交易。

常見的解決方法包括創建3個觸發器,2個語句級別--BEFORE和AFTER操作,以及一個行級別(有不少文章描述此方法,例如https://asktom.oracle.com/pls/asktom/ASKTOM.download_file?p_file=6551198119097816936)。

+0

謝謝,修正了,但還是想着如何解決它,也許把它分成兩個觸發器。 – 2014-11-24 15:44:40

+0

2觸發器不會有幫助 - 您需要按照文章中的描述使用3。另一種選擇是創建存儲過程,將數據插入'B'並打印所需的信息。然後,您可以撤銷除存儲過程之外的任何人的插入權限。注意:你的4個選項可以用一個替換。 – a1ex07 2014-11-24 15:58:05

1

你忘了最後的END;只是錯字,但在其他情況下:

錯誤:PLS-00405:子查詢不允許在此上下文中 當您使用IN運算符調用IF時。

你必須改變你的,如果像這樣:

select count(1) into l_count From A where color='red' and Name = :new.name; 

if (l_count>0) THEN .... 
    DBMS_OUTPUT.PUT_LINE('There are '.... 
end if; 
+0

謝謝,修正了,但還是想着如何解決它,也許把它分成兩個觸發器。 – 2014-11-24 15:44:14

相關問題