diff --git a/2207/触发器练习题.md b/2207/触发器练习题.md index e64d47c..3746123 100644 --- a/2207/触发器练习题.md +++ b/2207/触发器练习题.md @@ -314,6 +314,26 @@ VALUES(DEFAULT, '雷昊', 60000.00, '2022-12-31', 1, 1, NULL); 创建一个触发器 `before_department_delete`,在删除 `department` 表数据之前,检查该部门是否还有员工。如果有员工,阻止删除并抛出错误。 +```sql +DELIMITER $$ +DROP TRIGGER IF EXISTS before_department_delete; +CREATE TRIGGER before_department_delete +BEFORE DELETE ON department +FOR EACH ROW +BEGIN + IF (SELECT COUNT(*) FROM employee e WHERE e.dept_id = OLD.dept_id) > 0 THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = '该部门有员工无法删除'; + END IF; +END $$ +DELIMITER ; + +DELETE FROM department +WHERE dept_id = 1; +``` + + + #### 练习题 9: 自动更新职位工资范围 创建一个触发器 `after_job_update`,在更新 `job` 表的 `min_salary` 或 `max_salary` 字段后,自动调整 `employee` 表中相关员工的工资,使其符合新的工资范围。