我试图使用MySQL在触发器中编写业务规则,但它不起作用。
我想要做的是,如果条件为false,则插入必须失败并回滚它。问题是MySQL不允许在触发器中使用回滚。
我还试图使用SIGNAL和短信,但它失败了。
代码是:
CREATE TRIGGER tr_NewTeacher
AFTER INSERT ON teachers FOR EACH ROW
BEGIN
IF (salary > 1300 AND budget < 15000)
BEGIN
ROLLBACK TRANSACTION;
END
END
答案 0 :(得分:0)
在MySQL触发器中,如果失败,将回滚事务。
所以,你必须在触发器体内引发异常:
...
if [Test]
then
SIGNAL sqlstate '45001' set message_text = "No way ! You cannot do this !";
end if ;
...
答案 1 :(得分:0)
您应该使用before insert
并获取需要使用的列值new
因此触发器将为
delimiter //
create trigger tr_NewTeacher before insert on teacher
for each row
begin
if new.salaRY>1300 AND new.budget<15000 then
signal sqlstate '45000' set message_text = 'Your error message';
end if;
end;//
delimiter ;
以下是mysql中的测试用例
mysql> create table teacher (id int auto_increment primary key,salaRY int , budget int);
Query OK, 0 rows affected (0.17 sec)
mysql> delimiter //
mysql> create trigger tr_NewTeacher before insert on teacher
-> for each row
-> begin
-> if new.salaRY>1300 AND new.budget<15000 then
-> signal sqlstate '45000' set message_text = 'Your error message';
-> end if;
-> end;//
Query OK, 0 rows affected (0.14 sec)
mysql> insert into teacher (salaRY,budget) values (1200,16000);
Query OK, 1 row affected (0.04 sec)
mysql> insert into teacher (salaRY,budget) values (1400,13000);
ERROR 1644 (45000): Your error message
mysql> select * from teacher ;
+----+--------+--------+
| id | salaRY | budget |
+----+--------+--------+
| 1 | 1200 | 16000 |
+----+--------+--------+
1 row in set (0.00 sec)