创建最大值允许触发器

时间:2015-02-18 12:39:23

标签: mysql sql triggers

我尝试创建一个触发器,只要在表中达到某个值就会执行ROLLBACK TRANSACTION。

想象一下,一个uni图书馆的学生只能同时拥有5个活跃贷款。我该如何实现这种触发?

这是我们到目前为止所做的:

CREATE DEFINER = CURRENT_USER TRIGGER `bib_db`.`Customer_AFTER_UPDATE` AFTER UPDATE ON `Customer` FOR EACH ROW 

if activeloans <5
AND Customertype = student
then

  SIGNAL sqlstate '45001' set message_text = "You've reached your maximum ammount of loans";
ROLLBACK TRANSACTION
end if ; 
end

我可能会离开,但就我而言......任何人都有任何想法?

1 个答案:

答案 0 :(得分:0)

两件重要的事情。首先,您应该使用before更新触发器来阻止更新发生。其次,逻辑是倒退的。更像是:

DELIMITER //
CREATE DEFINER = CURRENT_USER TRIGGER bib_db.Customer_BEFORE_UPDATE
BEFORE UPDATE ON `Customer`
FOR EACH ROW 
BEGIN
    if activeloans >= 5 AND Customertype = 'student' then
        SIGNAL sqlstate '45001' set message_text = "You've reached your maximum ammount of loans";
    end if ; 
END;

DELIMITER ;