我在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 ;
答案 0 :(得分:1)
您错过了关键字 DEFAULT
。使用0
代替NULL
。
DECLARE total_sale INT DEFAULT 0;
答案 1 :(得分: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
设为唯一字段。
答案 2 :(得分: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 ;