2

複数の行に挿入する前にトリガーを作成したい。新しいデータを挿入する前に、以前のバージョンのデータを ID で削除したいと考えています。

例えば:

CREATE OR REPLACE TRIGGER mytableTrigger
BEFORE INSERT ALL ON mytable
BEGIN
    DELETE FROM mytable WHERE column2 = fooId; --I want to get fooId in here.
END;

INSERT ALL
  INTO mytable (column1, column2, column3) VALUES (Seq.nextval(), fooId, 'val1.3')
  INTO mytable (column1, column2, column3) VALUES (Seq.nextval(), fooId, 'val2.3')
  INTO mytable (column1, column2, column3) VALUES (Seq.nextval(), fooId, 'val3.3')
SELECT * FROM dual;

単純な行レベルのトリガーであれば、:new.fooId で fooId を取得できます。しかし、そうではありません。では、INSERT ALL Trigger の ID を取得または付与できますか?

THX。

4

2 に答える 2

5

INSERT ALL is a special case of INSERT, it will fire standard BEFORE/AFTER INSERT triggers.

You would need ON EACH ROW triggers to access the values of the row you are inserting. (un)Fortunately, you can't use row triggers to query the table you are trying to modify: you will run into ORA-04091. See this recent question for why you should not use triggers if you want to do this kind of logic.

Use procedures. Easier to code, easier to maintain and debug. Triggers are the GOTO of database logic.

Here's a similar advice from Tom Kyte:

anyway, you can do too much work in triggers, this may well be that time -- there is nothing wrong with doing things in a more straightforward fashion (eg: using a stored procedure to implement your transaction) [...]
The logic is a whole lot more understandable that way (and maintainable and testable and everything)


With hindsight your case is even more complicated than what I thought at the beginning. Now my understanding of your requirement is: you want your statement to first remove all rows that will have the fooID identifier, then insert another set of rows. However, the number of rows could be different so a standard row-per-row approach won't work.

I'm now not even sure you could do this with triggers, even if you persisted with this approach !

于 2013-03-06T15:52:01.363 に答える
1

同じ文字起こしステートメントからテーブルが挿入されると同時に、テーブルを削除または更新できる信頼性の高いリレーショナルデータベースを知りません。
しかし、これはあなたがやりたいことです。これは、ミューテーションテーブルと呼ばれます。
オラクルがこれを許可しないことを私は知っています。
あなたの例では、挿入時にいくつかのデータを挿入したいので、再帰的な操作があります。
解決策は、トリガーパルを使用することではありません。

于 2013-03-06T16:00:09.450 に答える