MySQL增删改教师触发器
时间: 2024-10-24 19:00:48 浏览: 20
MySQL中的触发器是一种特殊的存储过程,它会在特定的数据库操作(如INSERT、UPDATE或DELETE)执行前后自动运行。对于教师表(通常假设包含字段如`teacher_id`, `name`, `subject`等),你可以创建触发器来自动执行一些额外的操作,比如:
1. **插入触发器** (INSERT TRIGGER):当新教师信息被添加时,可以设置一个触发器检查是否有可用的教师ID或是否需要自动生成新的ID。
```sql
CREATE TRIGGER insert_teacher_trigger
BEFORE INSERT ON teacher
FOR EACH ROW
BEGIN
IF NEW.teacher_id IS NULL THEN
SET NEW.teacher_id = AUTO_INCREMENT;
END IF;
END;
```
2. **更新触发器** (UPDATE TRIGGER):例如,如果你想在教师名字更改时更新相关的课程记录,可以这样做:
```sql
CREATE TRIGGER update_subject_trigger
AFTER UPDATE OF name ON teacher
FOR EACH ROW
BEGIN
UPDATE course SET teacher_name = NEW.name WHERE teacher_id = OLD.teacher_id;
END;
```
3. **删除触发器** (DELETE TRIGGER):当删除一名教师时,可能希望同时从课程表中删除他们的关联记录。
```sql
CREATE TRIGGER delete_course_trigger
AFTER DELETE ON teacher
FOR EACH ROW
BEGIN
DELETE FROM course WHERE teacher_id = OLD.teacher_id;
END;
```
阅读全文