加入收藏 | 设为首页 | 会员中心 | 我要投稿 东莞站长网 (https://www.0769zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

MySQL触发器未正确检查变量

发布时间:2021-02-25 15:05:26 所属栏目:MySql教程 来源:网络整理
导读:我是MySQL触发器的新手,并且如果条目无效,则想防止条目存储在数据库中.在这种情况下,我想检查模块年份是否大于课程中的年份. 这是我的过程(此过程在插入之前执行). SELECT num_of_years INTO @num_years FROM courses WHERE courses.course_id = NEW.course_

我是MySQL触发器的新手,并且如果条目无效,则想防止条目存储在数据库中.在这种情况下,我想检查模块年份是否大于课程中的年份.

这是我的过程(此过程在插入之前执行).

SELECT num_of_years INTO @num_years FROM courses WHERE courses.course_id = NEW.course_id;

IF NEW.course_year > @num_years THEN
UPDATE `Error: invalid_id_test` SET x=1;
END;

为什么这允许任何课程年份入学,我该如何解决? 最佳答案 编辑:修改后的答案,现在我更好地理解了问题.

这是一个测试.

create table courses (
  course_id int primary key,num_of_years tinyint unsigned default 1
);

create table modules (
  module_id int primary key,course_id int,course_year tinyint unsigned
);

delimiter ;;
create trigger t before insert on modules for each row 
begin 
  declare num_years tinyint unsigned; 
  select num_of_years into num_years from courses where course_id = NEW.course_id; 
  if NEW.course_year > num_years then 
    signal sqlstate '45000' 
      set message_text = 'course_year is larger than the course length'; 
  end if; 
end;;
delimiter ;

这种作品:

insert into courses set course_id=1,num_of_years=3;

insert into modules values set module_id=1,course_id1,course_year=4;
ERROR 1644 (45000): course_year is larger than the course length

但是,如果courses.num_of_years为NULL,则不会阻止INSERT.

insert into courses set course_id=2,num_of_years=NULL;

insert into modules set module_id=2,course_id=2,course_year=99;
Query OK,1 row affected (0.01 sec)

原因是触发器中的变量为NULL,因此NEW.course_year> num_years不正确,不会引发异常.

要解决此问题,请检查NULL.

delimiter ;;
create trigger t before insert on modules for each row 
begin 
  declare num_years tinyint unsigned; 
  select num_of_years into num_years from courses where course_id = NEW.course_id; 
  if num_years is NULL or NEW.course_year > num_years then 
    signal sqlstate '45000' 
      set message_text = 'course_year is larger than the course length'; 
  end if; 
end;;
delimiter ;

insert into modules set module_id=2,course_year=99;
ERROR 1644 (45000): course_year is larger than the course length

如果您尝试为找不到的course_id插入模块,这也会引发错误.同样,这将使num_years为NULL,因此我们需要在触发器中进行检查.

insert into modules set module_id=2,course_id=5,course_year=99;
ERROR 1644 (45000): course_year is larger than the course length

(编辑:东莞站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读