Syntax error Implement MySQL trigger in the first table to insert records in the second table?

Implement MySQL trigger in the first table to insert records in the second table?



For this, the syntax is as follows −

DELIMITER //
create trigger yourTriggerName before insert on yourTableName1
   for each row
   begin
         insert into yourTableName2 values (yourValue1,yourValue2,...N);
end ;
//
DELIMITER ;

Let us first create a table −

mysql> create table DemoTable1
(
   StudentId int,
   StudentName varchar(40)
);
Query OK, 0 rows affected (0.69 sec)

Here is the query to create second table −

mysql> create table DemoTable2(
   Id int,
   Name varchar(40)
);
Query OK, 0 rows affected (0.61 sec)

Here is the query for trigger before insert −

mysql> DELIMITER //
mysql> create trigger afterinserttrigger before insert on DemoTable1 for each row
   begin
      insert into DemoTable2 values (10,'Chris');
   end ;
//
Query OK, 0 rows affected (0.13 sec)
mysql> DELIMITER ;

Let us insert the record into first table −

mysql> insert into DemoTable1 values(1,'David');
Query OK, 1 row affected (0.21 sec)

Now you can display all records from the first table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | David       |
+-----------+-------------+
1 row in set (0.00 sec)

Let us check the table records of second table −

mysql> select *from DemoTable2;

This will produce the following output −

+------+-------+
| Id   | Name  |
+------+-------+
|   10 | Chris |
+------+-------+
1 row in set (0.00 sec)
Updated on: 2019-10-09T12:34:23+05:30

226 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements