编写存储过程,对学生成绩表进行插入操作,并通过触发器保证插入时,学号与学生情况表中的学号字段一致,课程号与课程表中对应字段一致。其中触发器分别用后触发器和替代触发器实现。
时间: 2024-05-28 16:15:16 浏览: 292
好的,这是一个关于数据库的问题,以下是代码示例:
存储过程:
CREATE PROCEDURE insert_score
(
@studentId INT,
@courseId INT,
@score DECIMAL(4,2)
)
AS
BEGIN
INSERT INTO score (student_id,course_id,score)
VALUES (@studentId,@courseId,@score)
END
后触发器:
CREATE TRIGGER student_id_match ON score AFTER INSERT
AS
BEGIN
IF NOT EXISTS (SELECT * FROM student_info WHERE student_info.student_id IN (SELECT student_id FROM inserted))
BEGIN
RAISERROR('The inserted student ID does not exist in the student_info table!',16,1)
ROLLBACK TRAN
RETURN
END
END
CREATE TRIGGER course_id_match ON score AFTER INSERT
AS
BEGIN
IF NOT EXISTS (SELECT * FROM course_info WHERE course_info.course_id IN (SELECT course_id FROM inserted))
BEGIN
RAISERROR('The inserted course ID does not exist in the course_info table!',16,1)
ROLLBACK TRAN
RETURN
END
END
替代触发器:
CREATE TRIGGER student_id_match ON score INSTEAD OF INSERT
AS
BEGIN
IF NOT EXISTS (SELECT * FROM student_info WHERE student_info.student_id IN (SELECT student_id FROM inserted))
BEGIN
RAISERROR('The inserted student ID does not exist in the student_info table!',16,1)
ROLLBACK TRAN
RETURN
END
ELSE
BEGIN
INSERT INTO score (student_id,course_id,score)
SELECT student_id,course_id,score FROM inserted
END
END
CREATE TRIGGER course_id_match ON score INSTEAD OF INSERT
AS
BEGIN
IF NOT EXISTS (SELECT * FROM course_info WHERE course_info.course_id IN (SELECT course_id FROM inserted))
BEGIN
RAISERROR('The inserted course ID does not exist in the course_info table!',16,1)
ROLLBACK TRAN
RETURN
END
ELSE
BEGIN
INSERT INTO score (student_id,course_id,score)
SELECT student_id,course_id,score FROM inserted
END
END
希望以上代码能够帮到您!
阅读全文