我正在尝试创建一个触发器。首先,我创建了表员工和表employees_audit:
CREATE TABLE employees (
employeeNumber int(11) NOT NULL,
lastName varchar(50) NOT NULL,
firstName varchar(50) NOT NULL,
extension varchar(10) NOT NULL,
email varchar(100) NOT NULL,
officeCode varchar(10) NOT NULL,
reportsTo int(11) default NULL,
jobTitle varchar(50) NOT NULL,
PRIMARY KEY (employeeNumber)
)
CREATE TABLE employees_audit (
id int(11) NOT NULL AUTO_INCREMENT,
employeeNumber int(11) NOT NULL,
lastname varchar(50) NOT NULL,
changedon datetime DEFAULT NULL,
action varchar(50) DEFAULT NULL,
PRIMARY KEY (id)
)
然后我创建了触发器:
DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW BEGIN
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedon = NOW(); 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 'DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employe' at line 1
我的代码中是否有任何错误或我是否需要其他MySQL版本?
答案 0 :(得分:0)
你是从phpMyAdmin运行的吗?如果是这样,分隔符应设置在SQL textarea下面的字段中,而不是在文本区域中。
不。与已删除的答案相反,;
之后不需要DELIMITER $$
,因为这会将分隔符设置为$$;
答案 1 :(得分:0)
mysql> CREATE TABLE employees_audit (
-> id int(11) NOT NULL AUTO_INCREMENT,
-> employeeNumber int(11) NOT NULL,
-> lastname varchar(50) NOT NULL,
-> changedon datetime DEFAULT NULL,
-> action varchar(50) DEFAULT NULL,
-> PRIMARY KEY (id)
-> )
->
-> DELIMITER $$
-> CREATE TRIGGER before_employee_update
-> BEFORE UPDATE ON employees
-> FOR EACH ROW BEGIN
-> INSERT INTO employees_audit
-> SET action = 'update',
-> employeeNumber = OLD.employeeNumber,
-> lastname = OLD.lastname,
-> changedon = NOW(); END$$
错误1064(42000):您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本,以便在'DELIM附近使用正确的语法 ITER $$
RANG A BELL?看得类似吗?
Buddy,您(很可能)忘记在 create table 指令的末尾添加;
。以下代码有效:
mysql>
mysql> CREATE TABLE employees_audit (
-> id int(11) NOT NULL AUTO_INCREMENT,
-> employeeNumber int(11) NOT NULL,
-> lastname varchar(50) NOT NULL,
-> changedon datetime DEFAULT NULL,
-> action varchar(50) DEFAULT NULL,
-> PRIMARY KEY (id)
-> );
Query OK, 0 rows affected (0.09 sec)
mysql>
mysql> DELIMITER $$
mysql> CREATE TRIGGER before_employee_update
-> BEFORE UPDATE ON employees
-> FOR EACH ROW BEGIN
-> INSERT INTO employees_audit
-> SET action = 'update',
-> employeeNumber = OLD.employeeNumber,
-> lastname = OLD.lastname,
-> changedon = NOW(); END$$
Query OK, 0 rows affected (0.01 sec)
mysql> DELIMITER ;
OLD ANSWER
试试这个
DELIMITER $$
CREATE TRIGGER before_employee_update BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedon = NOW();
END;$$
DELIMITER ;
在;
之后遗失END
,我想,
击>
编辑:修复了foramtting
Edit1 :重新回答。