时间:2021-07-01 10:21:17 帮助过:2人阅读
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;
mysql 触发器
标签: