Wednesday, June 25, 2014

Create and use trigger in MySQL




Suppose we have users table:

CREATE TABLE users
(
user_id int NOT NULL,
salary int NOT NULL DEFAULT 0,
PRIMARY KEY (user_id)
)

We can create a trigger salary_sum
CREATE TRIGGER salary_sum BEFORE INSERT ON users FOR EACH ROW SET @sum = @sum + NEW.salary;

When we execute an insert statement on users table, the trigger salary_sum is excuted:


mysql> SET @sum = 0;
mysql> INSERT INTO users VALUES('andy',2000),('dave',2500),('terry',3000);
mysql> SELECT @sum AS 'Total salary inserted';
+-----------------------+
| Total salary inserted |
+-----------------------+
| 7500               |
+-----------------------+

No comments:

Post a Comment