Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR SQL

mysql trigger

CREATE TABLE test1(a1 INT);
CREATE TABLE test2(a2 INT);
CREATE TABLE test3(a3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
CREATE TABLE test4(
  a4 INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  b4 INT DEFAULT 0
);

delimiter //
CREATE TRIGGER name_of_trigger [BEFORE|AFTER] [INSERT|UPDATE|DELETE] 
ON test1
FOR EACH ROW
BEGIN
	/* 
    Examples of code to write 
    */
	[INSERT|DELETE|UPDATE|IF|ELSEIF|END IF];
    /* 
    NEW.a1 meanse the new value that will be added with INSERT into test1
    */
    INSERT INTO test2 SET a2 = NEW.a1;
    DELETE FROM test3 WHERE a3 = NEW.a1;
    UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
    IF NEW.a1 < 0 THEN
    	SET NEW.a1 = 0;
    ELSEIF NEW.a1 > 100 THEN
    	SET NEW.a1 = 100;
    END IF;
END//
delimiter;
Source by dev.mysql.com #
 
PREVIOUS NEXT
Tagged: #mysql #trigger
ADD COMMENT
Topic
Name
5+2 =