(1)在两个表间建立为维护参照完整性使用的级联删除触发器、级联修改触发器和受限插入触发器。 (2)建立一个学生选课数不超5门的触发器; (3)建立一个触发器,教授工资不得低于4000元,若低于4000,自动改为4000元。 (4)建立一个触发器,当对表SC的grade属性修改时,若分数增加了10%,则将此次操作记录到另一个表SC_U(sno,cno,Oldgrade,Newgrade)中,其中Oldgrade修改前的分数,Newgrade修改后的分数。
时间: 2024-01-22 09:19:02 浏览: 108
(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
```
阅读全文