測試表1
?
1
2
3
4
5
6
7
8
DROP TABLE IF EXISTS test;
CREATE TABLE test (
id bigint(11) unsigned NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL DEFAULT '',
type varchar(100),
create_time datetime,
PRIMARY KEY (ID)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
測試表2
?
1
2
3
4
5
6
7
8
9
DROP TABLE IF EXISTS test_hisy;
CREATE TABLE test_hisy (
id bigint(11) unsigned NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL DEFAULT '',
type varchar(100),
create_time datetime,
operation varchar(100) COMMENT '操作類型',
PRIMARY KEY (ID)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
insert觸發器
表test新增記錄後,將type值為“1”的記錄同時插入到test_hisy表中(AFTER INSERT:錄入後觸發, BEFORE INSERT:錄入前觸發)
?
1
2
3
4
5
6
7
8
9
10
11
DELIMITER //
DROP TRIGGER IF EXISTS t_after_insert_test//
CREATE TRIGGER t_after_insert_test
AFTER INSERT ON test
FOR EACH ROW
BEGIN
IF new.type='1' THEN
insert into test_hisy(name, type, create_time, operation)
values(new.name, new.type, new.create_time, 'insert');
END IF;
END;//
update觸發器
表test修改時,若type值為“2”則將修改前的記錄同時插入到test_hisy表中(AFTER UPDATE:修改後觸發, BEFORE UPDATE:修改前觸發)
?
1
2
3
4
5
6
7
8
9
10
11
DELIMITER //
DROP TRIGGER IF EXISTS t_before_update_test//
CREATE TRIGGER t_before_update_test
BEFORE UPDATE ON test
FOR EACH ROW
BEGIN
IF new.type='2' THEN
insert into test_hisy(name, type, create_time, operation)
values(old.name, old.type, old.create_time, 'update');
END IF;
END;//
delete觸發器
表test刪除記錄前,將刪除的記錄錄入到表test_hisy中(AFTER DELETE:刪除後觸發, BEFORE DELETE:刪除前觸發)
?
1
2
3
4
5
6
7
8
9
DELIMITER //
DROP TRIGGER IF EXISTS t_before_delete_test//
CREATE TRIGGER t_before_delete_test
BEFORE DELETE ON test
FOR EACH ROW
BEGIN
insert into test_hisy(name, type, create_time, operation)
values(old.name, old.type, old.create_time, 'delete');
END;//
注:以上觸發器例子中出現的new為修改後的數據, old為修改前的數據