Update MySQL table on INSERT command with triggers?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable1
   -> (
   -> Id int,
   -> FirstName varchar(20)
   -> );
Query OK, 0 rows affected (0.52 sec)

Here is the query to create second table −

mysql> create table DemoTable2
   -> (
   -> EmployeeId int,
   -> EmployeeName varchar(20)
   -> );
Query OK, 0 rows affected (0.51 sec)

Let us now create a trigger to update MySQL table on insert command −

mysql>  DELIMITER //
mysql>     CREATE TRIGGER updateDemoOnInsert
   ->      AFTER INSERT ON DemoTable2
   ->         FOR EACH ROW BEGIN
   ->         insert into DemoTable1 values(110,'Adam');
   ->         END
   ->      //
Query OK, 0 rows affected (0.14 sec)
mysql> DELIMITER ;
 

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(101,'Mike');
Query OK, 1 row affected (0.22 sec)

Display all records from the second table using select statement −

mysql> select * from DemoTable2;

This will produce the following output −

+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
|        101 | Mike         |
+------------+--------------+
1 row in set (0.00 sec)

Display all records from the first table using select statement −

mysql> select * from DemoTable1;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
|  110 | Adam      |
+------+-----------+
1 row in set (0.00 sec)
raja
Published on 12-Dec-2019 06:36:44
Advertisements