From 1b42d49ba9ea1532d5ef9224ea71c3b0d6a31643 Mon Sep 17 00:00:00 2001 From: smallkun Date: Thu, 20 Mar 2025 18:57:01 +0800 Subject: [PATCH] Auto commit --- 2207/触发器练习题.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/2207/触发器练习题.md b/2207/触发器练习题.md index 08a557b..77ae40a 100644 --- a/2207/触发器练习题.md +++ b/2207/触发器练习题.md @@ -120,6 +120,35 @@ SET MESSAGE_TEXT = '错误消息'; 创建一个触发器 `before_employee_insert`,在插入 `employee` 表数据之前,检查员工的工资是否在其对应职位的 `min_salary` 和 `max_salary` 范围内。如果超出范围,阻止插入并抛出错误。 +```sql +DELIMITER $$ +DROP TRIGGER IF EXISTS before_employee_insert; +CREATE TRIGGER before_employee_insert +BEFORE INSERT ON employee +FOR EACH ROW +BEGIN + + IF NEW.salary < ( + SELECT j.max_salary + FROM job j + WHERE j.job_id = NEW.job_id + ) OR NEW.salary > ( + SELECT j.min_salary + FROM job j + WHERE j.job_id = NEW.job_id + ) THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = '工资值错误,不在职务工资范围内'; + END IF; +END $$ +DELIMITER ; + +INSERT INTO employee +VALUES(DEFAULT, '雷昊', 0, NOW(), 1, 1); +``` + + + #### 练习题 2: 自动更新部门人数 创建一个触发器 `after_employee_insert`,在插入 `employee` 表数据之后,自动更新 `department` 表中的部门人数(假设 `department` 表新增一个字段 `employee_count`)。