Pages

Thursday, December 22, 2011

How to create trigger on mysql

mysql
Trigger is a procedure that automatically run when the trigger was invoked. For example: deleting data on a table will trigger a trigger to delete data on other tables. Below is an example of using triggers in MySQL database :
delimiter $$ 
create trigger auto_insert_test2
before insert on test for each row
begin
  insert into test2 (test_code, test_name) values (NEW.test_code,NEW.test_name);
end$$
 
create trigger auto_update_test2
before update on test for each row
begin
  update test2 set test_name=NEW.test_name where test_code=NEW.test_code;
end$$
 
create trigger auto_delete_test2
before delete on test for each row
begin
delete from test2 where test_code=OLD.test_code;
delete from trans where trans_test_code=OLD.test_code;
end$$
delimiter ;
In this code, it's assumed that we have 3 tables : test, test2 and trans.

No comments:

Post a Comment

Don't Forget To Join Our Community
×
Widget