为course表创建一个级联删除触发器:当从course中删除某课程信息,同时删除表sc中与此课程相关的选课记录
时间: 2024-02-25 18:53:12 浏览: 154
好的,下面是一个示例触发器的代码,供您参考:
```
CREATE TRIGGER delete_sc
AFTER DELETE ON Course
FOR EACH ROW
BEGIN
DELETE FROM Sc WHERE C_no = OLD.C_no;
END;
```
这个触发器会在 Course 表上进行 DELETE 操作时自动触发。在触发器中,使用 OLD 参数来访问被删除的数据行。通过将 Sc 表中与被删除课程相关的选课记录删除,即可完成级联删除的操作。
需要注意的是,触发器的行为可能会影响数据库性能,因此在使用触发器时需要谨慎考虑。
相关问题
创建一个级联修改触发器trigger_1,即当修改学生课程表Course中的某门课的课程号时,对应学生的选课表SC中的课程号也作修改
你的问题是关于数据库的触发器(trigger)的。下面是一个级联修改触发器的示例代码,可以满足你的需求:
```
CREATE TRIGGER trigger_1
AFTER UPDATE ON Course
FOR EACH ROW
BEGIN
UPDATE SC SET CourseNo = NEW.CourseNo WHERE StudentID = NEW.StudentID AND CourseNo = OLD.CourseNo;
END;
```
当Course表中某一行的课程号被修改时,触发器会将对应学生的选课表SC中的课程号也作出相应修改。这个触发器是一个AFTER UPDATE触发器,意味着它会在Course表中的修改操作完成之后执行。每次更新Course表中的一行时,触发器会检查是否有学生已经选过该门课程,如果有,就将学生选课表中的该门课程的课程号更新为新的课程号。
(1)在两个表间建立为维护参照完整性使用的级联删除触发器、级联修改触发器和受限插入触发器。 (2)建立一个学生选课数不超5门的触发器; (3)建立一个触发器,教授工资不得低于4000元,若低于4000,自动改为4000元。 (4)建立一个触发器,当对表SC的grade属性修改时,若分数增加了10%,则将此次操作记录到另一个表SC_U(sno,cno,Oldgrade,Newgrade)中,其中Oldgrade修改前的分数,Newgrade修改后的分数。
(1)建立级联删除触发器:
```
CREATE TRIGGER tr_del_course
ON course
FOR DELETE
AS
BEGIN
DELETE FROM score WHERE cno IN (SELECT cno FROM deleted)
END
```
```
CREATE TRIGGER tr_del_student
ON student
FOR DELETE
AS
BEGIN
DELETE FROM score WHERE sno IN (SELECT sno FROM deleted)
END
```
建立级联修改触发器:
```
CREATE TRIGGER tr_update_course
ON course
FOR UPDATE
AS
BEGIN
UPDATE score SET cno = inserted.cno WHERE cno IN (SELECT cno FROM deleted)
END
```
```
CREATE TRIGGER tr_update_student
ON student
FOR UPDATE
AS
BEGIN
UPDATE score SET sno = inserted.sno WHERE sno IN (SELECT sno FROM deleted)
END
```
建立受限插入触发器:
```
CREATE TRIGGER tr_insert_score
ON score
FOR INSERT
AS
BEGIN
IF (SELECT COUNT(*) FROM score WHERE sno = inserted.sno) >= 5
RAISERROR ('每个学生最多只能选5门课程!', 16, 1)
END
```
(2)建立学生选课数不超过5门的触发器:
```
CREATE TRIGGER tr_insert_score
ON score
FOR INSERT
AS
BEGIN
DECLARE @sno CHAR(10)
SET @sno = (SELECT sno FROM inserted)
IF (SELECT COUNT(*) FROM score WHERE sno = @sno) >= 5
BEGIN
RAISERROR ('每个学生最多只能选5门课程!', 16, 1)
ROLLBACK TRANSACTION
END
END
```
(3)建立教授工资不得低于4000元的触发器:
```
CREATE TRIGGER tr_update_teacher
ON teacher
FOR UPDATE
AS
BEGIN
IF EXISTS (SELECT * FROM inserted WHERE salary < 4000)
BEGIN
UPDATE teacher SET salary = 4000 WHERE tid IN (SELECT tid FROM inserted WHERE salary < 4000)
END
END
```
(4)建立当对表SC的grade属性修改时,若分数增加了10%,则将此次操作记录到另一个表SC_U(sno,cno,Oldgrade,Newgrade)中的触发器:
```
CREATE TRIGGER tr_update_score
ON score
FOR UPDATE
AS
BEGIN
DECLARE @sno CHAR(10), @cno CHAR(10), @Oldgrade DECIMAL(5,2), @Newgrade DECIMAL(5,2)
SELECT @sno = sno, @cno = cno, @Oldgrade = deleted.grade, @Newgrade = inserted.grade
FROM inserted INNER JOIN deleted ON inserted.sno = deleted.sno AND inserted.cno = deleted.cno
IF @Newgrade > @Oldgrade * 1.1
BEGIN
INSERT INTO SC_U (sno, cno, Oldgrade, Newgrade) VALUES (@sno, @cno, @Oldgrade, @Newgrade)
END
END
```
阅读全文