开发者

Solving the mutating table problem in Oracle SQL produces a deadlock

开发者 https://www.devze.com 2023-02-13 13:13 出处:网络
Hey, I\'m trying to create a trigger in my Oracle database that changes all other records except the one that has just been changed and launched the trigger to 0. Because I am updating records in the

Hey, I'm trying to create a trigger in my Oracle database that changes all other records except the one that has just been changed and launched the trigger to 0. Because I am updating records in the same table as the one that launched the trigger I got the mutating table error. To solve this, I put the code as an anonymous transaction, however this causes a deadlock.

Trigger code:

CREATE OR REPLACE TRIGGER check_thumbnail AFTER INSERT OR UPDATE OF thumbnail ON photograph
FOR EACH ROW
BEGIN
  IF :new.thumbnail = 1 THEN
    check_thumbnail_set_others(:new.url);
  END IF;
END;

Procedure code:

CREATE OR REPLACE PROCEDURE check_thumbnail_set_others(p_ur开发者_Python百科l IN VARCHAR2)
IS PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
    UPDATE photograph SET thumbnail = 0 WHERE url <> p_url;
    COMMIT;
END;

I assume I'm causing a deadlock because the trigger is launching itself within itself. Any ideas?


Using an autonomous transaction for this sort of thing is almost certainly a mistake. What happens if the transaction that inserted the new thumbnail needs to rollback? You've already committed the change to the other rows in the table.

If you want the data to be transactionally consistent, you would need multiple triggers and some way of storing state. The simplest option would be to create a package with a collection of thumbnail.url%type then create three triggers on the table. A before statement trigger would clear out the collection. A row-level trigger would insert the :new.url value into the collection. An after statement trigger would then read the values from the collection and call the check_thumbnail_set_others procedure (which would not be an autonomous transaction).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号