我在 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 ;