0

我在 MySQL 中有这个触发器

DROP TRIGGER IF EXISTS BeforeGivingRight;
DELIMITER $$
CREATE TRIGGER BeforeGivingRight
BEFORE INSERT ON right_code 
FOR EACH ROW
BEGIN
    DECLARE num_rows INT NULL;
    SELECT count(right_code) FROM valid_rights WHERE right_code  =
                                            new.user_right.right INTO num_rows;

    IF num_rows = 0
    THEN
        set msg = concat('Error: That right is not allowed!',
                                      cast(new.user_right.right as char));
        signal sqlstate '45000' set message_text = msg;
    END IF;
END $$
DELIMITER ;

它给了我这个错误

#1064 - You have an error in your SQL syntax; check the manual that corresponds 
    to your MySQL server version for the right syntax to use near 'NULL; SELECT
    count(right_code) FROM valid_rights WHERE right_code  = new.user_' at line 5 

这里有什么问题?我想要做的是,在我插入一些权利(例如 201)之前valid_rights,使用触发器检查它是否存在。

编辑(答案)

因此,当您想要一个引发异常的触发器时,您可以使用:

DROP TRIGGER IF EXISTS BeforeGivingRight;
DELIMITER $$
CREATE TRIGGER BeforeGivingRight
BEFORE INSERT ON user_rights 
FOR EACH ROW
BEGIN
    DECLARE num_rows INT DEFAULT NULL;
    DECLARE msg VARCHAR(32) DEFAULT "";
    SELECT count(valid_rights.right_code) FROM valid_rights WHERE right_code  = new.right INTO num_rows;

    IF num_rows = 0
    THEN
        set msg = concat('Error: That right is not allowed!', cast(new.right as char));
        signal sqlstate '45000' set message_text = msg;
    END IF;
END $$
DELIMITER ;
4

3 回答 3

1

你错过了关键字 DEFAULT。使用0而不是NULL.

DECLARE total_sale INT DEFAULT 0;

请参阅此处:存储过程中的变量

于 2012-10-04T08:28:29.200 回答
0

因此,当您想要一个引发异常的触发器时,您可以使用:

DROP TRIGGER IF EXISTS BeforeGivingRight;
DELIMITER $$
CREATE TRIGGER BeforeGivingRight
BEFORE INSERT ON user_rights 
FOR EACH ROW
BEGIN
    DECLARE num_rows INT DEFAULT NULL;
    DECLARE msg VARCHAR(32) DEFAULT "";
    SELECT count(valid_rights.right_code) FROM valid_rights WHERE right_code  = new.right INTO num_rows;

    IF num_rows = 0
    THEN
        set msg = concat('Error: That right is not allowed!', cast(new.right as char));
        signal sqlstate '45000' set message_text = msg;
    END IF;
END $$
DELIMITER ;
于 2012-10-04T13:55:35.107 回答
0

作为一种解决方法:如果表是 InnoDb,那么您可以使用外键来限制不存在的值。只需将外键添加到user_rights表中,服务器就会引发错误。

例如 -

ALTER TABLE right_code
  ADD CONSTRAINT FK_right_code FOREIGN KEY (`right`)
    REFERENCES valid_rights(right_code) ON DELETE RESTRICT ON UPDATE RESTRICT;

另外,使字段valid_rights. right_code唯一的,如果不是。

于 2012-10-04T09:17:12.353 回答