-
Notifications
You must be signed in to change notification settings - Fork 0
/
NotesTriggers.txt
79 lines (57 loc) · 1.72 KB
/
NotesTriggers.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
NotesTriggers
Mysql trigger syntax
CREATE TRIGGER name
[BEFORE, AFTER] [INSERT, UPDATE, DELETE] ON TableName
FOR EACH ROW (this can be one or more rows)
SET NEW.salary = (NEW.hourly_pay * 2080);
SHOW TRIGGERS;
# Modify one record on this table
UPDATE employees
SET hourly_pay = 50
WHERE employee_id = 1;
SELECT * FROM employees;
# Modify all records on this table by adding 1 to each row
UPDATE employees
SET hourly_pay = hourly_pay + 1
SELECT * FROM employees;
# Before insert when creating a new record
CREATE TRIGGER before_hourly_pay_insert
BEFORE INSERT ON employees
FOR EACH ROW
SET NEW.salary = (NEW.hourly_pay * 2080);
========================================================
Example:
CREATE TABLE expenses (
expense_id int primary key,
expense_name varchar(50),
expense_total decimal (10, 2);
INSERT INTO expenses
VALUE (1, "salaries", 0),
(2, "supplies", 0),
(3, "taxed", 0);
# Add total for column salary from employees table
UPDATE expenses
SET expense_total = (SELECT SUM(salary) FROM employees)
WHERE expense_name = "salaries";
# Turn this function into a trigger for Create, Update and delete
# This updates on delete
CREATE TRIGGER after_salary_delete
AFTER DELETE ON employees
FOR EACH ROW
UPDATE expenses
SET expense_total = expense_total - OLD.salary
WHERE expense_namme = "salaries";
# This updates on create
CREATE TRIGGER after_salary_insert
AFTER INSERT ON employees
FOR EACH ROW
UPDATE expenses
SET expense_total = expense_total + NEW.salary
WHERE expense_name = "salaries"
# This will update expense salaries on update
CREATE TRIGGER after_salary_update
AFTER UPDATE ON employees
FOR EACH ROW
UPDATE expenses
SET expense_total = expense_total + (NEW.salary - OLD.salary)
WHERE expense_name = "salaries";