-
Notifications
You must be signed in to change notification settings - Fork 546
/
Copy path16.01.Database Triggers.sql
78 lines (62 loc) · 1.47 KB
/
16.01.Database Triggers.sql
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
75
76
77
78
CREATE DATABASE trigger_demo;
use trigger_demo;
CREATE TABLE users(
username VARCHAR(50),
age INT);
/*CREATION demo trigger*/
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('adam',20);
/*Error Code: 1644. must be an adult!*/
INSERT INTO users(username,age)
VALUES('bob',15);
/*DELETE demo trigger*/
DROP TRIGGER must_be_adult;
/*-------------------------------------------*/
/* follower id cannot equal to followee id */
DELIMITER $$
CREATE TRIGGER follower_trigger
BEFORE INSERT ON follows FOR EACH ROW
BEGIN
IF NEW.follower_id = NEW.followee_id
THEN
SIGNAL SQLSTATE '45000'
SET message_text = 'Follower Id cannot be same as Followee Id !';
END IF;
END;
$$
DELIMITER ;
/*-------------------------------------------*/
/*log the history of unfollow cases VERSION 1*/
DELIMITER $$
CREATE TRIGGER capture_unfollow
AFTER DELETE ON follows FOR EACH ROW
BEGIN
INSERT INTO unfollows(follower_id,followee_id)
VALUES(OLD.follower_id,OLD.followee_id);
END;
$$
DELIMITER ;
/*log the history of unfollow cases VERSION 2*/
DELIMITER $$
CREATE TRIGGER capture_unfollow
AFTER DELETE ON follows FOR EACH ROW
BEGIN
INSERT INTO unfollows
SET follower_id = OLD.follower_id,
followee_id = OLD.followee_id;
END;
$$
DELIMITER ;
/*-------------------------------------------*/