INSERT:将新行插入表时激活触发程序,例如,通过INSERT、LOAD DATA和REPLACE语句。
UPDATE:更改某一行时激活触发程序,例如,通过UPDATE语句。
DELETE:从表中删除某一行时激活触发程序,例如,通过DELETE和REPLACE语句。
举例:
创建表
CREATE TABLE `employee` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
`createTime` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DELIMITER ;;
CREATE TRIGGER `employee_tri`
BEFORE INSERT #插入前触发
ON `employee`
FOR EACH ROW
begin
#createTime为系统当前时间
set new.createTime=current_timestamp;
if new.age<17 then
#年龄小于17,将设为17
set new.age=17;
elseif new.age>65 then
#年龄大于65,将设为65
set new.age=65;
end if;
end;;
DELIMITER ;
运行结果:
mysql> insert into employee(name,age,createTime) values('linchunda',13,'1990-06-12');
Query OK, 1 row affected (0.03 sec)
mysql> select * from employee;
+----+-----------+-----+---------------------+
| id | name | age | createTime |
+----+-----------+-----+---------------------+
| 1 | linchunda | 17 | 2013-08-01 21:32:14 |
+----+-----------+-----+---------------------+
1 row in set (0.00 sec)
想插入年龄小于17的都不行,触发器自动置为17,创建时间自动为系统当前的时间
OLD.col_name修改或删除它之前的值。
提示:如果是Ms SQL Server分别保存在inserted表、deleted表
创建删除触发器
删除一条记录后,将在history表添加一条相应的记录
#创建history表,该表结构和employee一样,但没有数据,因为没有id=-1的记录
CREATE TABLE HISTORY SELECT * FROM employee where id=-1;
DELIMITER ;;
CREATE TRIGGER `employee_tri_del`
BEFORE DELETE #删除前触发
ON `employee`
FOR EACH ROW
begin
#把该条记录插入history表
INSERT INTO HISTORY SELECT * FROM employee where id=OLD.id;
end;;
DELIMITER ;
mysql> delete from employee where id =1;
Query OK, 1 row affected (0.03 sec)
mysql> select * from history;
+----+-----------+-----+---------------------+
| id | name | age | createTime |
+----+-----------+-----+---------------------+
| 1 | linchunda | 17 | 2013-08-01 21:32:14 |
+----+-----------+-----+---------------------+
1 row in set (0.00 sec)
mysql> select * from employee;
Empty set (0.00 sec)
DROP TRIGGER `employee_tri`;
注:
mysql5.1.6版本之前,您必须要拥有SUPER权限,之后的版本因为触发器与一个数据表相关联,所以您必须拥有那个数据表的trigger权限才能为它创建和删除触发器。