Showing posts with label mysql. Show all posts
Showing posts with label mysql. Show all posts

Thursday, March 2, 2017

Triger in sql

In simplicity Trigger's are used to perform some database operation if any defined event occurs on a specific table. Trigger call on Insert, Update and delete operation on before/after these event completed. To grab data we have to keyword new and old.
INSERT: new
UPDATE: new/old
DELETE: old

Syntax for creating trigger:
CREATE TRIGGER triger_name
BEFORE | AFTER event ON table_name
BEGIN
...
END;


example:

DELIMITER $$
CREATE TRIGGER updatedata
    AFTER UPDATE ON employees
    FOR EACH ROW
BEGIN
    UPADTE history
    SET old_sal=old.sal where emp_id=old.emp_id;
END$$
DELIMITER ;

DELIMITER $$
CREATE TRIGGER name_add
    BEFORE UPDATE ON employees
    FOR EACH ROW
BEGIN
    SET new.name=concat(new.salut,' ',new.fname,' ',new.lname);
END$$
DELIMITER ;

mysql> delimiter //
mysql> CREATE TRIGGER upd_check BEFORE UPDATE ON account
    -> FOR EACH ROW
    -> BEGIN
    ->     IF NEW.amount < 0 THEN
    ->         SET NEW.amount = 0;
    ->     ELSEIF NEW.amount > 100 THEN
    ->         SET NEW.amount = 100;
    ->     END IF;
    -> END;//
mysql> delimiter ;


sql to see all triggers : SHOW TRIGGERS;
sql to drop trigger: DROP TRIGGER trigger_name;