当我尝试在 mysql 中创建触发器时出现语法错误
Posted
技术标签:
【中文标题】当我尝试在 mysql 中创建触发器时出现语法错误【英文标题】:Syntax Error when I try to create trigger in mysql 【发布时间】:2021-01-31 19:30:25 【问题描述】:我正在尝试为审计日志创建触发器,其中插入 manageMemberLog
并且 action
列等于 CREATE
,然后插入 users
表的关联列,然后抓取选择新创建的行并获取用户 ID,然后将其余数据插入配置文件,但是当我尝试提交查询时收到此错误消息。
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'END' at line 9
第 9 行 = 结束 IF;
我尝试仔细重新输入我写的内容,但同样的错误消息。
更新:使用了格式,它说WHERE userID = @newUserID
是错误,我仍然不明白,因为我从选择中获取数据并将值设置为@newUserID。
DELIMITER $$
CREATE TRIGGER usersDB_ai AFTER INSERT
ON manageMemberLog
FOR EACH ROW
IF NEW.action = 'CREATE' THEN
INSERT INTO users (firstName, lastName, userName, email, pwd) VALUES (NEW.firstName, NEW.lastName, NEW.userName, NEW.email, NEW.pwd);
SET @newUserID := (SELECT userID FROM users WHERE userName = NEW.userName AND email = NEW.email);
UPDATE profiles SET rankID = NEW.rankID WHERE userID = @newUserID;
END IF;
END$$
DELIMITER ;
相关表:
CREATE TABLE `users` (
`userID` int(11) NOT NULL,
`firstName` varchar(128) NOT NULL,
`lastName` varchar(128) NOT NULL,
`userName` varchar(128) NOT NULL,
`email` varchar(128) NOT NULL,
`pwd` varchar(128) NOT NULL
)
DELIMITER $$
CREATE TRIGGER `userCreated` AFTER INSERT ON `users` FOR EACH ROW BEGIN
INSERT INTO profiles (userID) VALUES(NEW.userID);
END
$$
DELIMITER ;
CREATE TABLE `profiles` (
`profileID` int(11) NOT NULL,
`userID` int(11) NOT NULL,
`rankID` int(11) NOT NULL,
...
)
CREATE TABLE `manageMemberLog` (
`manageMemberLogID` int(11) NOT NULL,
`manageDate` datetime NOT NULL,
`managerID` int(11) DEFAULT NULL,
`action` varchar(6) CHARACTER SET utf8mb4 NOT NULL,
`userID` int(11) DEFAULT NULL,
`firstName` varchar(128) CHARACTER SET utf8mb4 NOT NULL,
`lastName` varchar(128) CHARACTER SET utf8mb4 NOT NULL,
`userName` varchar(128) CHARACTER SET utf8mb4 NOT NULL,
`email` varchar(128) CHARACTER SET utf8mb4 NOT NULL,
`pwd` varchar(128) CHARACTER SET utf8mb4 NOT NULL,
`rankID` int(11) NOT NULL
)
谁能帮忙提前谢谢!
【问题讨论】:
【参考方案1】:我很傻,所以出了问题的是我忘记在 FOR EACH ROW 之后写“BEGIN”,并且不涉及它所说的任何错误。错误消息有时不可靠,但我想 END
确实有帮助。更好的错误消息是you can't end when it never began.
所以正确的查询是:
DELIMITER $$
CREATE TRIGGER usersDB_ai AFTER INSERT
ON manageMemberLog
FOR EACH ROW BEGIN
IF NEW.action = 'CREATE' THEN
INSERT INTO users (firstName, lastName, userName, email, pwd) VALUES (NEW.firstName, NEW.lastName, NEW.userName, NEW.email, NEW.pwd);
SET @newUserID := (SELECT userID FROM users WHERE userName = NEW.userName AND email = NEW.email);
UPDATE profiles SET rankID = NEW.rankID WHERE userID = @newUserID;
END IF;
END$$
DELIMITER ;
【讨论】:
以上是关于当我尝试在 mysql 中创建触发器时出现语法错误的主要内容,如果未能解决你的问题,请参考以下文章
当我尝试在 /Library/Application Support/ 中创建文件夹“efiLinq”时出现权限被拒绝错误
尝试编写 MySQL 触发器以替换 phpmyadmin 上的 CHECK 约束时出现语法错误