Auto commit
This commit is contained in:
parent
a3837c3a77
commit
b030ae136a
@ -475,22 +475,106 @@ DELIMITER ;
|
||||
|
||||
创建一个触发器 `after_employee_update`,在更新 `employee` 表的 `job_id` 字段后,将变更记录插入到一个新的日志表 `job_change_log` 中,记录员工 ID、旧职位 ID、新职位 ID 和变更时间。
|
||||
|
||||
```sql
|
||||
CREATE TABLE job_change_log(
|
||||
emp_id INT,
|
||||
old_job_id INT,
|
||||
new_job_id INT,
|
||||
update_date DATE
|
||||
);
|
||||
DELIMITER $$
|
||||
DROP TRIGGER IF EXISTS after_employee_update;
|
||||
CREATE TRIGGER after_employee_update
|
||||
AFTER UPDATE ON employee
|
||||
FOR EACH ROW
|
||||
BEGIN
|
||||
IF NEW.job_id <> OLD.job_id THEN
|
||||
INSERT INTO job_change_log()
|
||||
VALUES(NEW.emp_id, OLD.job_id, NEW.job_id, NOW());
|
||||
END IF;
|
||||
END $$
|
||||
DELIMITER ;
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### 练习题 16: 防止删除职位
|
||||
|
||||
创建一个触发器 `before_job_delete`,在删除 `job` 表数据之前,检查该职位是否还有员工。如果有员工,阻止删除并抛出错误。
|
||||
|
||||
```sql
|
||||
DELIMITER $$
|
||||
DROP TRIGGER IF EXISTS before_job_delete;
|
||||
CREATE TRIGGER before_job_delete
|
||||
BEFORE DELETE ON employee
|
||||
FOR EACH ROW
|
||||
BEGIN
|
||||
IF (SELECT COUNT(*) FROM employee WHERE job_id = OLD.job_id) > 0 THEN
|
||||
SIGNAL SQLSTATE '45000'
|
||||
SET MESSAGE_TEXT = '该职位还有员工';
|
||||
END IF;
|
||||
END $$
|
||||
DELIMITER ;
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### 练习题 17: 自动更新部门平均工资
|
||||
|
||||
创建一个触发器 `after_employee_insert`,在插入 `employee` 表数据之后,自动更新 `department` 表中的部门平均工资(假设 `department` 表新增一个字段 `avg_salary`)。
|
||||
|
||||
```sql
|
||||
DELIMITER $$
|
||||
DROP TRIGGER IF EXISTS after_employee_insert;
|
||||
CREATE TRIGGER after_employee_insert
|
||||
AFTER INSERT ON employee
|
||||
FOR EACH ROW
|
||||
BEGIN
|
||||
UPDATE department d
|
||||
SET d.avg_salary = (SELECT AVG(e.salary) FROM employee e WHERE d.dept_id = e.dept_id)
|
||||
WHERE NEW.dept_id = d.dept_id;
|
||||
|
||||
END $$
|
||||
DELIMITER ;
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### 练习题 18: 防止插入未来入职日期
|
||||
|
||||
创建一个触发器 `before_employee_insert`,在插入 `employee` 表数据时,检查 `hire_date` 是否晚于当前日期。如果是,阻止插入并抛出错误。
|
||||
|
||||
```sql
|
||||
DELIMITER $$
|
||||
DROP TRIGGER IF EXISTS before_employee_insert;
|
||||
CREATE TRIGGER before_employee_insert
|
||||
BEFORE INSERT ON employee
|
||||
FOR EACH ROW
|
||||
BEGIN
|
||||
IF NEW.hire_date < CURDATE() THEN
|
||||
SIGNAL SQLSTATE '45000'
|
||||
SET MESSAGE_TEXT = '入职日期不得晚于当前日期';
|
||||
END IF;
|
||||
|
||||
END $$
|
||||
DELIMITER ;
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### 练习题 19: 自动生成员工编号
|
||||
|
||||
创建一个触发器 `before_employee_insert`,在插入 `employee` 表数据时,自动生成一个唯一的员工编号(格式为 `EMP-年份-序号`,例如 `EMP-2023-001`),并将其存储到一个新字段 `emp_code` 中。
|
||||
|
||||
```sql
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### 练习题 20: 记录员工离职
|
||||
|
||||
创建一个触发器 `after_employee_delete`,在删除 `employee` 表数据之后,将被删除的员工信息插入到一个离职记录表 `employee_exit_log` 中,记录员工 ID、姓名、离职时间和原因(假设原因由用户输入)。
|
||||
|
||||
```sql
|
||||
```
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user