Trigger example to insert into table data from another table in different databases

A SQL trigger is a set of  SQL statements stored in the database catalog. A SQL trigger is executed or fired whenever an event associated with a table occurs e.g.,  insert, update or delete.
A SQL trigger is a special type of stored procedure. It is special because it is not called directly like a stored procedure. The main difference between a trigger and a stored procedure is that a trigger is called automatically when a data modification event is made against a table whereas a stored procedure must be called explicitly.
It is important to understand SQL trigger’s advantages and disadvantages so that you can use it appropriately. In the following sections, we will discuss about the advantages and disadvantages of using SQL trigger

CREATE TRIGGER `db1`.trig AFTER INSERT ON `db1`.t1 FOR EACH ROW INSERT INTO `db2`.t1(id,NAME) VALUES(new.id, new.name);

See Example below :

CREATE DATABASE db1;
CREATE DATABASE db2;
USE db1;
CREATE TABLE t1(id INT(10), NAME VARCHAR(25));
USE db2;
CREATE TABLE t1(id INT(10), NAME VARCHAR(25));
DROP TRIGGER trig;
CREATE TRIGGER `db1`.trig AFTER INSERT ON `db1`.t1 FOR EACH ROW INSERT INTO `db2`.t1(id,NAME) VALUES(new.id, new.name);
USE db1;
INSERT INTO `db1`.t1 VALUES(102,'roni');
SELECT * FROM `t1`

Comments

Popular posts from this blog

Script For Login, Logout and View Using PHP, MySQL and Bootstrap

Real-Time Web Interface to MQTT using Socket.io and Node.js

Customize radio buttons and checkboxes with CSS sprites