Submit Your Site To The Web's Top 50 Search Engines for Free!       ExactSeek: Relevant Web Search

Visitors

Flag Counter

Total Pageviews

Thursday, December 13, 2012

Create Triggers in MySQL - Tutorial 1

What are triggers? What are they used for? A trigger is a set of code which is executed in response to some event. E.g Update employee_perfomance table when a new task is inserted in task table. Here, the trigger is “update” and the event is “inserting a new row”. A trigger in MySQL is created using CREATE TRIGGER trigger_name. We need to specify the trigger type. Triggers can be used for actively control, monitor, and manage a group of tables whenever an insert, update, or delete operation is performed.


A database trigger is procedural code that is automatically executed in response to certain events on a particular table or view in a database. The trigger is mostly used for maintaining the integrity of the information on the database. For example, when a new record (representing a new worker) is added to the employees table, new records should also be created in the tables of the taxes, vacations and salaries.

CREATE TABLE table1(field1 CHAR);
CREATE TABLE table2(field2 CHAR);
CREATE TABLE table3(field3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
CREATE TABLE table4(
  field4 INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  field5 INT DEFAULT 0
);

delimiter |

CREATE TRIGGER tg_table1 BEFORE INSERT ON table1
 FOR EACH ROW BEGIN
    INSERT INTO table2 SET field2 = NEW.field1;
    DELETE FROM table3 WHERE field3 = NEW.field1;
    UPDATE table4 SET field4 = field5 * 10 WHERE field5 = NEW.field1;
  END;
|

0 comments

Post a Comment

loading