我尝试通过在phpmyadmin中将行插入数据库后组合字段来创建ID。我在以下触发器语句的第3行收到错误:
DROP TRIGGER IF EXISTS `scanID2`;
CREATE DEFINER=`root`@`localhost`
TRIGGER `scanID2`
AFTER INSERT ON db_name.`scan_data`
FOR EACH ROW
BEGIN
UPDATE db_name.scan_data
SET @data1 = concat(RIGHT(scanContent,2), RIGHT(operatorID,2), RIGHT(deviceID,2), RIGHT (scanDate, '-', ''), REPLACE (scanTime, ':', ''));
INSERT INTO db_name.scan_data(scanID) VALUES (@data1);
END
//
错误是:
#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 'CREATE DEFINER=`root`@`localhost`
TRIGGER `scanID2`
AFTER INSERT ON db_name' at line 2
好的,所以我想出了如何执行查询。触发器已经创建,但我不认为它做了它应该做的事情。记录不会更新。这是新代码:
BEGIN
SET @data1 = concat(RIGHT(scanContent,2), RIGHT(operatorID,2), RIGHT(deviceID,2), REPLACE (scanDate, '-', ''), REPLACE (scanTime, ':', ''));
INSERT INTO vacseen1_connect.scan_data(scanID) VALUES (@data1);
END
答案 0 :(得分:0)
有几件事需要考虑:
BEFORE
事件代替AFTER
触发器。这样,您可以在插入行的同时设置scanID
的值。NEW
关键字访问正在插入的行的字段。BEGIN ... END
阻止。REPLACE
用于scanDate。尝试
CREATE TRIGGER scanID2
BEFORE INSERT ON scan_data
FOR EACH ROW
SET NEW.scanID = CONCAT(
RIGHT(NEW.scanContent, 2),
RIGHT(NEW.operatorID, 2),
RIGHT(NEW.deviceID, 2),
REPLACE(NEW.scanDate, '-', ''),
REPLACE (NEW.scanTime, ':', '')
);
这是 SQLFiddle 演示