(jlive)[crashcourse]>CREATE TRIGGER newproduct AFTER INSERT ON products FOR EACH ROW BEGIN END;
Query OK, 0 rows affected (0.00 sec)
删除trigger
(jlive)[crashcourse]>DROP TRIGGER newproduct;
Query OK, 0 rows affected (0.00 sec)
trigger只能删除后重建,不能直接修改
INSERT Trigger
CREATE TABLE orders_log
(
change_id int NOT NULL AUTO_INCREMENT,
changed_on datetime NOT NULL,
change_type char(1) NOT NULL,
order_num int NOT NULL,
PRIMARY KEY (change_id)
)ENGINE=Aria;
DELIMITER //
CREATE TRIGGER neworder
AFTER INSERT ON
orders
FOR EACH ROW
BEGIN
INSERT INTO orders_log(changed_on, change_type, order_num)
VALUES(Now(),'A', NEW.order_num);
END;//
DELIMITER ;
在AFTER INSERT中有一个特殊的表变更NEW,只要有新记录插入orders表,则在记录插入之后将对就的字段写入到表orders_log中
(jlive)[crashcourse]>INSERT INTO orders(order_date, cust_id) VALUES(Now(), 10001);
Query OK, 1 row affected, 1 warning (0.00 sec)
(jlive)[crashcourse]>SELECT * FROM orders_log;
+-----------+---------------------+-------------+-----------+
| change_id | changed_on
+-----------+---------------------+-------------+-----------+
|
+-----------+---------------------+-------------+-----------+
1 row in set (0.00 sec)
DELETE Trigger
DELIMITER //
CREATE TRIGGER deleteorder BEFORE
DELETE ON
orders
FOR EACH ROW
BEGIN
INSERT INTO orders_log(changed_on, change_type, order_num)
VALUES(Now(),'D', OLD.order_num);
END;//
DELIMITER ;
(jlive)[crashcourse]>DELETE FROM orders WHERE order_num = 20010;
Query OK, 1 row affected, 1 warning (0.00 sec)
(jlive)[crashcourse]>SELECT * FROM orders_log;
+-----------+---------------------+-------------+-----------+
| change_id | changed_on
+-----------+---------------------+-------------+-----------+
|
|
+-----------+---------------------+-------------+-----------+
2 rows in set (0.00 sec)
删除前将OLD表中的对应记录写入到日志表
DELETE前先备份记录
CREATE TABLE orders_archive
(
order_date datetime NOT NULL,
cust_id int NOT NULL
) ENGINE=Aria;
DELIMITER //
CREATE OR REPLACE TRIGGER deleteorder BEFORE DELETE ON
orders
FOR EACH ROW
BEGIN
INSERT INTO orders_log(changed_on, change_type, order_num) VALUES(Now(),'D', OLD.order_num); -- log
INSERT INTO orders_archive(order_num, order_date, cust_id) VALUES(OLD.order_num, OLD.order_date, OLD.cust_id); -- backup
END;//
DELIMITER ;
UPDATE Trigger
(jlive)[crashcourse]>CREATE TRIGGER updatevendor BEFORE UPDATE ON vendors FOR EACH ROW SET NEW.vend_state = Upper(NEW.vend_state);
Query OK, 0 rows affected (0.16 sec)
(jlive)[crashcourse]>UPDATE vendors SET vend_state = 'new
york' WHERE vend_id = 1006;
Rows matched: 1
(jlive)[crashcourse]>SELECT vend_state FROM vendors WHERE vend_id = 1006;
+------------+
| vend_state |
+------------+
| NEW YORK
+------------+
1 row in set (0.15 sec)