MySQL语句对SC1表设计一个触发器,该触发器保证每个学生所选课程的总学分不超过12分。用MySQL语句验证此触发器。
时间: 2024-03-07 12:49:25 浏览: 73
可以使用如下的MySQL语句创建一个名为`check_credit`的触发器:
```mysql
DELIMITER //
CREATE TRIGGER check_credit
BEFORE INSERT ON SC1
FOR EACH ROW
BEGIN
DECLARE total_credit INT;
SELECT SUM(Credit) INTO total_credit FROM Course WHERE CourseID IN (SELECT CourseID FROM SC1 WHERE SID = NEW.SID);
IF total_credit + NEW.Credit > 12 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Selected courses exceed credit limit.';
END IF;
END//
DELIMITER ;
```
该触发器的作用是在每次向`SC1`表插入新记录之前,计算该学生已经选修的课程的学分总和,并且将新选修的课程学分加上去,如果超过12分,则触发器会抛出一个异常,阻止新记录的插入。
可以使用如下的MySQL语句验证该触发器:
```mysql
INSERT INTO SC1 (SID, CourseID, Credit) VALUES (1, 'C001', 5);
INSERT INTO SC1 (SID, CourseID, Credit) VALUES (1, 'C002', 6);
INSERT INTO SC1 (SID, CourseID, Credit) VALUES (1, 'C003', 2);
-- 这里应该会抛出异常,因为总学分已经超过了12分
INSERT INTO SC1 (SID, CourseID, Credit) VALUES (1, 'C004', 1);
```
阅读全文