创建一个mysql触发器,以在列更新时插入数据

时间:2016-09-13 03:59:07

标签: php mysql triggers

CREATE TRIGGER `update_2` 
AFTER UPDATE ON `itm_master`
FOR EACH ROW 
BEGIN
    IF NEW.transfer_status='YES' THEN
        INSERT into activity_tbl (`evnt_date`,`con_type`,`username`,`item_serial`,`item_model`,`item_type`,`to_status`)
        VALUES (now(),'Update',NEW.user,NEW.item_serial,NEW.master_item_model,NEW.master_item_type,NEW.item_status);
    END IF;
END

每当在item_master表中更新transfer_status字段时,我都想创建一个触发器,将数据插入到activity_tbl中。我使用此查询,但我收到Mysql错误

CREATE TRIGGER `update_2` 
AFTER UPDATE ON `itm_master`
FOR EACH ROW 
BEGIN
    IF NEW.transfer_status='YES' THEN
        INSERT into activity_tbl (`evnt_date`,`con_type`,`username`,`item_serial`,`item_model`,`item_type`,`to_status`)
        VALUES (now(),'Update',NEW.user,NEW.item_serial,NEW.master_item_model,NEW.master_item_type,NEW.item_status);

MySQL说:文档

  

1064 - Erreur desyntaxeprèdede''la la ligne 7

1 个答案:

答案 0 :(得分:0)

我让这个工作。我目前没有创意评论。

SCHEMA:

create table itm_master
(   id int auto_increment primary key,
    transfer_status VARCHAR(100) NOT NULL,
    user VARCHAR(100) NOT NULL,
    item_serial VARCHAR(100) NOT NULL,
    master_item_model VARCHAR(100) NOT NULL,
    master_item_type VARCHAR(100) NOT NULL,
    item_status VARCHAR(100) NOT NULL
);
create table activity_tbl
(   id int auto_increment primary key,
    `evnt_date` DATETIME NOT NULL,
    `con_type` VARCHAR(100) NOT NULL,
    `username` VARCHAR(100) NOT NULL,
    `item_serial` VARCHAR(100) NOT NULL,
    `item_model` VARCHAR(100) NOT NULL,
    `item_type` VARCHAR(100) NOT NULL,
    `to_status` VARCHAR(100) NOT NULL
);

TRIGGER:

DROP TRIGGER IF EXISTS update_2;
DELIMITER $$
CREATE TRIGGER `update_2` 
AFTER UPDATE ON `itm_master`
FOR EACH ROW 
BEGIN
    IF NEW.transfer_status='YES' THEN
        INSERT into activity_tbl (`evnt_date`,`con_type`,`username`,`item_serial`,`item_model`,`item_type`,`to_status`)
        VALUES (now(),'Update',NEW.user,NEW.item_serial,NEW.master_item_model,NEW.master_item_type,NEW.item_status);
    END IF;
END;$$
DELIMITER ;

测试:

INSERT itm_master(transfer_status, user, item_serial, master_item_model, master_item_type, item_status) values
('a','b','c','d','e','f');

UPDATE itm_master SET transfer_status='blah' WHERE id=1;
select * from activity_tbl;
-- no rows

UPDATE itm_master SET transfer_status='YES' WHERE id=1;
select * from activity_tbl;
+----+---------------------+----------+----------+-------------+------------+-----------+-----------+
| id | evnt_date           | con_type | username | item_serial | item_model | item_type | to_status |
+----+---------------------+----------+----------+-------------+------------+-----------+-----------+
|  1 | 2016-09-13 00:14:26 | Update   | b        | c           | d          | e         | f         |
+----+---------------------+----------+----------+-------------+------------+-----------+-----------+

PHPMyAdmin不需要DELIMITER包装器。