Simple Usage Example of MySQL Triggers

  • 2021-10-16 05:13:13
  • OfStack

This article illustrates the simple use of MySQL triggers. Share it for your reference, as follows:

mysql Triggers and Stored Procedures 1, is embedded in mysql 1 segment of the program, the trigger is triggered by events, these events include INSERT, UPDATE, DELETE, not including SELECT

Create Triggers


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

For example

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

Triggers with multiple execution statements


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);
// Begin testing 
INSERT INTO test1 VALUES (1), (3), (1), (7), (1), (8), (4), (4);

View Triggers


SHOW TRIGGERS \G; // View all 
SELECT * FROM information_schema.TRIGGERS where TRIGGER_NAME = 'testref';

Delete trigger


DROP TRIGGER testref;

Comprehensive case

Step 1: Create the persons table


CREATE TABLE persons (name VARCHAR(40), num int);

Step 2: Create a sales table sales


CREATE TABLE sales (name VARCHAR(40), sum int);

Step 3: Create a trigger


CREATE TRIGGER num_sum AFTER INSERT ON persons
FOR EACH ROW INSERT INTO sales VALUES (NEW.name,7*NEW.num);

Step 4: Insert records into the persons table


INSERT INTO persons VALUES ('xiaoxiao',20),('xiaohua',69);
SELECT * FROM persons;
SELECT *FROM sales;

More readers interested in MySQL can check out the topics on this site: "MySQL Query Skills Encyclopedia", "MySQL Transaction Operation Skills Summary", "MySQL Stored Procedure Skills Encyclopedia", "MySQL Database Lock Skills Summary" and "MySQL Common Functions Summary"

I hope this article is helpful to everyone's MySQL database.


Related articles: