mysql 触发器

mysql触发器和存储过程一样,是嵌入到mysql的一段程序,触发器是由事件来触发的,这些事件包括,INSERT,UPDATE,DELETE,不包括SELECT

创建触发器

CREATE TRIGGER name,time,event ON table_name FOR EACH ROW trigger_stmt

 例如

CREATE TRIGGER ins_sum BEFORE INSERT ON account FOR EACH ROW SET @sum = @sum + NEW.amount

 有多个执行语句的触发器

CREATE TABLE test1(a1 INT);
CREATE TABLE test2(a2 INT);
CREATE TABLE test3(a3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
CREATE TABLE test4(
    a4 INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    b4 INT DEFAULT 0
);

DELIMITER //

CREATE TRIGGER testref BEFORE INSERT ON test1
    FOR EACH ROW BEGIN
        INSERT INTO test2 SET a2 = NEW.a1;
	DELETE FROM test3 where a3 = NEW.a1;
        UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
    END
    //

DELIMITER ;

INSERT INTO test3(a3) VALUES (NULL), (NULL), (NULL), (NULL), (NULL), (NULL),(NULL), (NULL), (NULL), (NULL), (NULL), (NULL);

INSERT INTO test4(a4) VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0);

//开始测试
INSERT INTO test1 VALUES (1), (3), (1), (7), (1), (8), (4), (4);

 

查看触发器

SHOW TRIGGERS \G;  //查看所有
SELECT * FROM information_schema.TRIGGERS where TRIGGER_NAME = 'testref';

 

删除触发器

DROP TRIGGER testref;

 综合案例

步骤1:创建persons表
CREATE TABLE persons (name VARCHAR(40), num int);

步骤2:创建一个销售额表sales
CREATE TABLE sales (name VARCHAR(40), sum int);

步骤3:创建一个触发器
CREATE TRIGGER num_sum AFTER INSERT ON persons
FOR EACH ROW INSERT INTO sales VALUES (NEW.name,7*NEW.num);

步骤4:向persons表中插入记录
INSERT INTO persons VALUES ('xiaoxiao',20),('xiaohua',69);

SELECT * FROM persons;
SELECT *FROM sales;

 

posted @ 2015-07-27 11:48  笑笑别人  阅读(192)  评论(0编辑  收藏  举报