mysql创建触发器错误

时间:2016-08-07 10:04:12

标签: mysql laravel

在MyISAM引擎上创建触发器以执行外键检查时遇到问题。有什么建议?请在下面找到错误。

  

SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在'ERROR 1644(45000)附近使用正确的语法:Custom ForeignKeyError                       ELSEIF(第8行的SELECT CO'(SQL:

CREATE TRIGGER insert_user_permission                 
BEFORE INSERT ON user_permissions 
            FOR EACH ROW
            BEGIN
                IF (SELECT COUNT(*) FROM users WHERE users.id=new.user_id)= 0 THEN                        
                    SIGNAL SQLSTATE '45000' 
                    SET MESSAGE_TEXT = 'Custom ForeignKeyError'
                    ERROR 1644 (45000): Custom ForeignKeyError
                ELSEIF (SELECT COUNT(*) FROM permissions WHERE permissions.id=new.permission_id)= 0 THEN
                    SIGNAL SQLSTATE '45000' 
                    SET MESSAGE_TEXT = 'Custom ForeignKeyError'
                    ERROR 1644 (45000): Custom ForeignKeyError
                END IF;
            END;)

1 个答案:

答案 0 :(得分:1)

删除错误生成语句的最后一部分。只需使用

SIGNAL SQLSTATE '45000' 
SET MESSAGE_TEXT = 'Custom ForeignKeyError';

请勿忘记该声明末尾的;

根据您用来定义触发器的工具,您还需要定义另一个分隔符。

delimiter |

CREATE TRIGGER insert_user_permission                 
BEFORE INSERT ON user_permissions 
FOR EACH ROW
BEGIN
    IF (SELECT COUNT(*) FROM users WHERE users.id=new.user_id)= 0 THEN                        
        SIGNAL SQLSTATE '45000' 
        SET MESSAGE_TEXT = 'Custom ForeignKeyError';
    ELSEIF (SELECT COUNT(*) FROM permissions WHERE permissions.id=new.permission_id)= 0 THEN
        SIGNAL SQLSTATE '45000' 
        SET MESSAGE_TEXT = 'Custom ForeignKeyError';
    END IF;
END
|
delimiter ;