2012-02-10 73 views
3

我正在运行MySQL 5.5.9和InnoDB。无法更新在AFTER INSERT中执行的触发器表

我尝试创建一个版本化表,其中current字段指示记录是否为最新版本。喜欢的东西:

| autonumber | id | name | current 
| 1   | 1 | Yes | 0 
| 2   | 1 | No | 1 

无论如何,我通过一个AFTER INSERT触发与同一个ID current = 0更新中的所有记录MSSQL这样做,在过去经常。所以在这里,我们走在MySQL:

DELIMITER | 

CREATE TRIGGER TRIGGER_Products_UpdateEarlierVersions AFTER INSERT ON Products 
FOR EACH ROW BEGIN 
    UPDATE Products 
    SET current = 0 
    WHERE id = new.id 
     AND current = 1 
     AND autonumber <> new.autonumber; 
END; 
| 

这运行正常,但插入记录时:

insert into Products (id, name) 
values (1, "Hello SO!"); 

我收到以下错误:

Error Code: 1442. Can't update table 'Products' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

有没有解决的办法实现类似的事情?

回答

2

当你插入一条记录MySQL是做一些锁的东西从这里http://forums.mysql.com/read.php?99,122354,122505#msg-122505

when you insert a record mysql is doing some lock stuff. you can't insert/update/delete rows of the same table where you insert.. because then the trigger would called again and again.. ending up in a recursion

+0

我没有锁定,记录已经更新。 – 2012-02-10 12:08:45

+0

你正在锁定它:)))这是它的工作方式,如果你更新它被锁定的东西。行,页面,表格等。正如我写的尝试并使用BEFORE触发器。 – 2012-02-10 12:11:11

0

在MySQL中,无法更新在触发器中为其创建触发器的表('Products')。

根据MySQL文档,这个错误是为了防止无限递归而产生的:当UPDATE发生时,触发器运行并更新表,这个触发器UPDATE会导致触发器再次运行,并且一次又一次地结束在无限循环中。

+0

这就是错误的表白,而是我在寻找办法解决它。 – 2012-02-10 12:04:52

+0

最终尝试使用BEFORE触发器 – 2012-02-10 12:06:41

+1

你可以尝试在一个过程中做同样的更新工作吗? – 2012-02-10 12:11:32

0

服用。你不能插入/更新/删除你插入的同一张表的行。因为那么触发器会一次又一次地被调用。以递归结束

我曾经有这个问题。我删除了更新命令。所以,试试这个:

DELIMITER | 

CREATE TRIGGER TRIGGER_Products_UpdateEarlierVersions AFTER INSERT ON Products 
FOR EACH ROW BEGIN 

    SET current = 0 
    WHERE id = new.id 
     AND current = 1 
     AND autonumber <> new.autonumber; 
END; 
| 

我认为这是要去工作

相关问题