使用自动增量字段在插入触发器之前/之后 [英] Before / after insert trigger using auto increment field
本文介绍了使用自动增量字段在插入触发器之前/之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到了应该用于修复表中列的插入触发器的麻烦:
I'm having troubles with an insert trigger that is supposed to fix a column in a table:
id - auto increment int
thread_id - int [NULL]
我要实现的是将thread_id
设置为id
(如果插入为NULL).我失败了,因为:
What I want to achieve is to set the thread_id
to id
if it's inserted as NULL. I have failed because:
- 使用
before insert
触发器仍然没有id
的新值,并且神秘地将thread_id
设置为0 - 使用
after insert - update
触发器会引发合理的异常can't update table because it is already used by the statement
. - 您不能添加其他自动增量字段
- using
before insert
trigger still does not have the new value forid
and mysteriously setsthread_id
to 0 - using
after insert - update
trigger throws reasonable exceptioncan't update table because it is already used by the statement
. - you can not add additional auto increment field
该问题的解决方案是什么?
What is the solution to this problem?
推荐答案
DELIMITER $$
CREATE TRIGGER mytrigger BEFORE INSERT ON yourtable
FOR EACH ROW BEGIN
SET NEW.thread_id = IF(ISNULL(NEW.thread_id), 0, NEW.thread_id);
END;
$$
为了修改当前记录的值,您不使用UPDATE语句,而是使用NEW.columname
in order to modify values of the current record, you don't use UPDATE statement, you access them by using NEW.columname
这篇关于使用自动增量字段在插入触发器之前/之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文