触发在插入之前删除记录

时间:2017-06-02 18:42:36

标签: oracle11g sqlplus toad

我有一个包含4列的表

1.msisdn
2.accountnumber
3.cardnumber
4.subscriptiondate

我想在此表中添加触发器。如果我插入的数据是

1.99999999
2.2
3.3298572857239
4.(this can be blank)

并且表中当前的数据是

1.99999999
2.1
3.3298572857239
4.(this can be blank)

触发器应该检查是否存在此msisdn 99999999已经拥有此卡号3298572857239的记录。如果表中已存在记录,则触发器应删除现有条目并插入新条目。最终结果应如下所示

1.99999999
2.1
3.3298572857239
4.(this can be blank)

我想在触发器之前和之后保持accountnumber的值相同。这是我到目前为止所尝试的但是对于这个触发器,我没有在accountnumber列中获得任何数据。请有人帮忙

DROP TRIGGER TRIG_TABLEA;

CREATE OR REPLACE TRIGGER TRIG_TABLEA
BEFORE INSERT ON TABLEA 
REFERENCING OLD AS Old NEW AS New 
FOR EACH ROW
BEGIN
 :new.accountnumber := :old.accountnumber;
 DELETE FROM TABLEA WHERE MSISDN = :new.MSISDN AND CARDNUMBER = :new.CARDNUMBER;
 :new.MSISDN := :new.MSISDN;
 :new.CARDNUMBER := :new.CARDNUMBER;
 :new.accountnumber := :old.accountnumber;
END;
/

1 个答案:

答案 0 :(得分:5)

Don't do a delete-and-insert. You want MERGE. The only thing that can change in your statement is accountnumber and subscriptiondate. You don't say where the data is coming from, so I assume this is a PL/SQL procedure with p_* as the parameters. So you want something like this:

MERGE INTO mytable trg
USING ( SELECT p_accountnumber, p_subscriptiondate FROM dual ) src
   ON ( trg.msisdn = p_msisdn AND trg.cardnumber )
 WHEN NOT MATCHED INSERT ( msisdn, accountnumber, cardnumber, subscriptiondate )
      VALUES ( p_msisdn, p_accountnumber, p_cardnumber, p_subscriptiondate )
 WHEN MATCHED SET ( cardnumber = p_cardnumber, subscriptiondate = p_subscriptiondate)

This will do an insert if the row doesn't exist or update an existing row if it does.