简体   繁体   English

在更新时创建触发器以将旧值插入到MYSQL中的其他表中

[英]create trigger on update to insert old values into other table in MYSQL

I have two tables. 我有两张桌子。 The first is my person table which has id, name, creation_date as values, I have a old_person table (id, name, modified_date) which I want to populate the value of person before it actually changes. 第一个是我的person表,它有id,name,creation_date作为值,我有一个old_person表(id,name,modified_date),我想在实际更改之前填充person的值。 How would I go about that? 我该怎么办呢? I have tried triggers but failed. 我尝试过触发但失败了。

I tried as follows 我尝试如下

create trigger Person_Trigger Update on person
before update
as
insert into old_person(id, name, modified) 
select id, new.name, getdate()
from person

It's giving me syntax errors...Not many Trigger references out there either, a little push would be greatly appreciated! 它给了我语法错误...也没有很多触发器引用,一点推动将非常感激!

Have a look at the following example 看看下面的例子

SQL Fiddle DEMO SQL Fiddle DEMO

IO hade a bit of trouble myself, but from How to Create Triggers in MySQL there was a line that made me think IO自己有点麻烦,但是从MySQL中如何创建触发器有一条线让我思考

The first MySQL command we'll issue is a little unusual: 我们将发出的第一个MySQL命令有点不寻常:

DELIMITER $$ DELIMITER $$

Our trigger body requires a number of SQL commands separated by a semi-colon (;). 我们的触发器主体需要许多用分号(;)分隔的SQL命令。 To create the full trigger code we must change delimiter to something else — such as $$. 要创建完整的触发器代码,我们必须将分隔符更改为其他内容 - 例如$$。

Finally, we set the delimiter back to a semi-colon: 最后,我们将分隔符设置为分号:

DELIMITER ; DELIMITER;

So in the SQL Fiddle I changed the query terminator to GO and that seemed top work. 因此,在SQL Fiddle中,我将查询终止符更改为GO ,这似乎是最重要的工作。

CREATE TABLE person
(
  id INT,
  name varchar(20)
)
GO
CREATE TABLE old_person
(
  id INT,
  name varchar(20),
  modified DATETIME
)
GO
CREATE TRIGGER Person_Trigger before update on person
FOR EACH ROW BEGIN
  INSERT INTO old_person(id, name, modified) 
  VALUES (OLD.id, OLD.name, NOW());
END
GO



INSERT INTO person VALUES (1,'TADA')
GO

UPDATE person SET name = 'FOO'
GO

Try this: 试试这个:

DELIMITER \\
CREATE TRIGGER `Person_Trigger`
BEFORE UPDATE ON `Person`
FOR EACH ROW
BEGIN
DECLARE date_modified datetime;

SET date_modified = NOW();

INSERT INTO old_person(id, name, modified) 
VALUES (OLD.id, OLD.name, date_modified);
END\\

This syntax works for me on my own projects. 这个语法适用于我自己的项目。 You may also need to declare delimiters before you begin the trigger. 在开始触发之前,您可能还需要声明分隔符。 Also if you want to use the NEW keyword it should be AFTER update. 此外,如果你想使用NEW关键字应该是AFTER更新。 Switch to the OLD keyword if you are going to keep using BEFORE update on your trigger. 如果要继续在触发器上使用BEFORE更新,请切换到OLD关键字。

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

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