简体   繁体   English

创建UPDATE触发器时MySQL语法错误

[英]MySQL syntax error while creating a UPDATE Trigger

I am trying to create a trigger on updating the salary field of this table. 我正在尝试在更新此表的薪水字段时创建触发器。 customers(ID, Name, Age, Address, Salary) from this site SQL Trigger While creating it shows the following error 来自此站点的客户(ID,姓名,年龄,地址,薪水) SQL触发器创建时显示以下错误

MySQL said: MySQL说:
#1064 - You have an error in your SQL syntax; #1064-您的SQL语法有误; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'OR INSERT OR UPDATE ON customers FOR EACH ROW WHEN (NEW.ID > 0) DECLARE ' at line 2 检查与您的MariaDB服务器版本相对应的手册以获取正确的语法,以在第2行“(向新客户ID> 0进行声明时对客户进行插入或更新时)对附近使用”

Here is the code snippet: 这是代码片段:

BEFORE DELETE OR INSERT OR UPDATE ON customers 
FOR EACH ROW 
WHEN (NEW.ID > 0) 
DECLARE 
   sal_diff number; 
BEGIN `enter code here`
   sal_diff := :NEW.salary  - :OLD.salary; 
   dbms_output.put_line('Old salary: ' || :OLD.salary); 
   dbms_output.put_line('New salary: ' || :NEW.salary); 
   dbms_output.put_line('Salary difference: ' || sal_diff); 
END

Note that, I'm using phpMyAdmin. 请注意,我正在使用phpMyAdmin。 Does dbms_ouput.put_line() works there? dbms_ouput.put_line()在那工作吗?

As said in the comments, you are using Oracle syntax, it can't work on MySQL. 如评论中所述,您使用的是Oracle语法,它无法在MySQL上运行。

Then, there's no reason to have this trigger on DELETE and INSERT because your aim is to compute the salary difference on a specific row before and after it get updated. 然后,没有理由在DELETE和INSERT上触发该触发器,因为您的目的是在更新之前和之后的特定行上计算工资差异。 You can't have a value NEW on DELETE, and you can't have a value OLD on INSERT. 在DELETE上不能有新值,在INSERT上不能有OLD值。 Thus your computation is only meaningful on UPDATE. 因此,您的计算仅在UPDATE时有意义。

Here's the correct MySQL syntax (I am assuming that you have a column sal_diff on your table) 这是正确的MySQL语法(我假设您的表上有一列sal_diff

DELIMITER $$
CREATE TRIGGER `update_sal_diff`
BEFORE UPDATE ON `customers `
FOR EACH ROW
BEGIN
    SET NEW.sal_diff = NEW.salary  - OLD.salary;
END $$
DELIMITER ;

If this is not what you are trying to achieve, edit your question and add clear requirements 如果这不是您要实现的目标,请编辑问题并添加明确的要求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM