-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtriggers.sql
More file actions
59 lines (46 loc) · 1.35 KB
/
triggers.sql
File metadata and controls
59 lines (46 loc) · 1.35 KB
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
-- Triggers are SQL statements that are
-- AUTOMATICALLY RUN when a specific table is changed
-- CREATE TRIGGER name
-- trigger_time trigger_event ON table_name FOR EACH ROW
-- BEGIN
-- ...
-- END;
-- trigger_time
-- BEFORE or AFTER (the code is run before/after an insert/update/delete)
-- trigger_event
-- INSERT/UPDATE/DELETE
-- Triggers are used for validating data and enforcing specific things on it
-- To validate change we run code before inserting a row
DROP DATABASE IF EXISTS triggers_demo;
CREATE DATABASE triggers_demo;
USE triggers_demo;
CREATE TABLE users (
username VARCHAR(100),
age TINYINT
);
INSERT INTO users(username, age)
VALUES ('bobby', 23);
SELECT * FROM users;
-- 45000 - a generic state representing unhandled user-defined exception
-- we have to change delimiter because we need it in writing a trigger
-- that's why we change it to $$ and then to ; again
DELIMITER $$
CREATE TRIGGER must_be_adult
BEFORE INSERT ON users FOR EACH ROW
BEGIN
IF NEW.age < 18
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Must be an adult!';
END IF;
END;
$$
DELIMITER ;
INSERT INTO users(username, age)
VALUES ('JJ', 12); -- Error Code: 1644. Must be an adult!
-- Listing triggers
SHOW TRIGGERS;
-- Removing triggers
-- DROP TRIGGER <trigger_name>;
-- Triggers can make debugging hard!
-- Hidden things happen behind the scenes.