在sql sever中设计触发器,完成以下功能: 1. student表中当删除某一同学sno时,该同学的所有选课也都要删除,设计一个触发器完成此功能 2. student表中当插入某一同学sno时,若该同学的存在,则拒绝插入并提示“此记录无效”,设计一个触发器完成此功能 3. 在学生表Student上创建一个触发器,要求在向Student中插入数据或修改数据时,学生的年龄不得小于18岁,若小于18岁则将年龄改为18岁。 4. 在课程表Course中创建一个触发器,要求在删除一条课程记录时,先检查该课程是否有被选修记录,若有则提示出错,并回滚Rollback。 5. 创建和测试触发器:向SC表插入数据时,检查插入数据的课程号是否存在于Course表中(创建之前删除Cno的外键约束,比较外键约束和触发器之间的不同)
时间: 2023-12-19 17:07:43 浏览: 110
1. 触发器代码:
```
CREATE TRIGGER delete_student_courses
ON student
AFTER DELETE
AS
BEGIN
DELETE FROM SC WHERE Sno IN (SELECT Sno FROM deleted)
END
```
2. 触发器代码:
```
CREATE TRIGGER check_student_existence
ON student
INSTEAD OF INSERT
AS
BEGIN
IF EXISTS (SELECT * FROM student WHERE Sno = inserted.Sno)
BEGIN
RAISERROR ('此记录无效', 16, 1)
END
ELSE
BEGIN
INSERT INTO student (Sno, Sname, Ssex, Sage, Sdept)
SELECT Sno, Sname, Ssex, Sage, Sdept FROM inserted
END
END
```
3. 触发器代码:
```
CREATE TRIGGER check_student_age
ON student
FOR INSERT, UPDATE
AS
BEGIN
UPDATE student SET Sage = 18 WHERE Sage < 18
END
```
4. 触发器代码:
```
CREATE TRIGGER check_course_selection
ON course
INSTEAD OF DELETE
AS
BEGIN
IF EXISTS (SELECT * FROM SC WHERE Cno IN (SELECT Cno FROM deleted))
BEGIN
RAISERROR ('该课程有被选修记录,无法删除', 16, 1)
ROLLBACK TRANSACTION
END
ELSE
BEGIN
DELETE FROM course WHERE Cno IN (SELECT Cno FROM deleted)
END
END
```
5. 触发器代码:
```
DROP TRIGGER IF EXISTS check_sc_course
GO
CREATE TRIGGER check_sc_course
ON SC
FOR INSERT
AS
BEGIN
IF NOT EXISTS (SELECT * FROM course WHERE Cno IN (SELECT Cno FROM inserted))
BEGIN
RAISERROR ('课程号不存在于Course表中', 16, 1)
ROLLBACK TRANSACTION
END
END
```
需要注意的是,在第五个触发器中,需要先删除SC表中Cno的外键约束,才能创建该触发器。同时,触发器和外键约束的区别在于,触发器可以在插入或修改数据时进行一些自定义的逻辑操作,而外键约束只能保证插入的数据符合外键约束的要求,无法进行其他操作。
阅读全文