有如下需求,一张表中有一个字段,用于记录更新该条数据的时间。
表结构如下:
CREATE TABLE temp2
(
id int(11) PRIMARY KEY AUTO_INCREMENT,
name varchar(10),
updated_at timestamp NULL
)
我做了如下尝试。
尝试1,如下:
delimiter |
DROP TRIGGER IF EXISTS tri_temp_updated_at;
CREATE TRIGGER tri_temp_updated_at AFTER UPDATE ON temp2
FOR EACH ROW
BEGIN
UPDATE temp2 t SET t.updated_at=now() WHERE t.id=old.id;
END;
|
delimiter ;
创建完触发器后测试,会出现ERROR 1442 (HY000)错误。详细信息如下:
ERROR 1442 (HY000): Can't update table 'temp2' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
尝试2,如下:
delimiter |
DROP TRIGGER IF EXISTS tri_temp_updated_at;
CREATE TRIGGER tri_temp_updated_at BEFORE UPDATE ON temp2
FOR EACH ROW
BEGIN
DECLARE now_date timestamp;
SET now_date=now();
IF now_date!=old.updated_at
THEN
UPDATE temp2 t SET t.updated_at=now_date WHERE t.id=old.id;
END IF;
END;
|
delimiter ;
创建完触发器后测试,仍然会出现ERROR 1442 (HY000)错误。
尝试3,如下:
DROP TRIGGER tri_temp_updated_at;
delimiter |
DROP TRIGGER IF EXISTS tri_temp_updated_at;
CREATE TRIGGER tri_temp_updated_at BEFORE UPDATE ON temp2
FOR EACH ROW
BEGIN
SET NEW.updated_at = now();
END;
|
delimiter ;
创建完触发器后测试,通过。
该贴被Robin编辑于2014-9-3 14:24:39该贴由hui.chen转至本版2014-11-5 16:18:25
该贴由hui.chen转至本版2014-11-5 16:22:20