How to ceate MySQL Trigger before Insert?

MySQLMySQLi Database

For this, the syntax is as follows −

delimiter //
create trigger yourTriggerName before insert on yourTableName
   FOR EACH ROW
   BEGIN

   yourStatement1
   .
   .
   N
END
//
delimiter ;

To understand the above syntax, let us create a table −

mysql> create table DemoTable1919
   (
   Value int
   );
Query OK, 0 rows affected (0.00 sec)

Here is the query to create MySQL trigger before inserting −

mysql> delimiter //
mysql> create trigger sumis60 before insert on DemoTable1919
   FOR EACH ROW
   BEGIN
   declare custom_message varchar(256);
        IF (SELECT sum(Value) from DemoTable1919) = 60 THEN
           set custom_message= "cannot insert because sum(Value) is greater than 60";
             signal sqlstate '13500'
             set message_text= custom_message;
         END IF;
     END
     //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;

Now you can insert some records in the table using insert command and check the working of trigger −

mysql> insert into DemoTable1919 values(10);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1919 values(20);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1919 values(30);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1919 values(40);
ERROR 1644 (13500): cannot insert because sum(Value) is greater than 60
raja
Published on 30-Dec-2019 07:00:31
Advertisements