MYSQL触发器-存储更新的表数据

时间:2018-12-07 12:26:55

标签: mysql sql

我有一个表,用于跟踪员工工作的小时数。

    CREATE TABLE HOURLYWORKLOG (
EMPLOYEEREF               INT(5) NOT NULL,
ORDERREF                  INT(5) NOT NULL,
HOURSWORKED               VARCHAR(10),
TOTALPAY                  NUMERIC(10),
NOTES                     VARCHAR(10),
CONSTRAINT HOURLYWORKLOG_EMPLOYEES_FOREIGN_KEY FOREIGN KEY (EMPLOYEEREF) REFERENCES EMPLOYEES (EMPLOYEEREF),
CONSTRAINT HOURLYWORKLOG_ORDERS_FOREIGN_KEY FOREIGN KEY (ORDERREF) REFERENCES WORKORDER (ORDERREF));

我希望创建一个触发器,如果​​更新了工作小时数列,则将该数据存储在单独的表中。仔细阅读,我看不到任何能解释我需要做的事情,至少我不理解阅读后涉及的步骤。因此,我当前的解决方案是通过创建镜像表(使用不同的名称)

CREATE TABLE MODIFIEDHOURLYWORKLOG (
EMPLOYEEREF               INT(5) NOT NULL,
ORDERREF                  INT(5) NOT NULL,
HOURSWORKED               VARCHAR(10),
TOTALPAY                  NUMERIC(10),
NOTES                     VARCHAR(10));  

然后像这样创建触发器

CREATE TRIGGER MODIFIEDHWL ON HOURLYWORKLOG
AFTER INSERT
AS
BEGIN
INSERT INTO MODIFIEDHOURLYWORKLOG
(EMPLOYEEREF, ORDERREF, HOURSWORKED, TOTALPAY, NOTES)
SELECT I.EMPLOYEEREF, I.ORDERREF, I.HOURSWORKED, I.TOTALPAY, I.NOTES
FROM HOURLYWORKLOG T
INNER JOIN INSERTED I ON T.EMPLOYEEREF-I.EMPLOYEEREF
END;

这显然行不通,并抛出错误,提示我的语法不正确。我不确定如何编写触发器以将数据从原始表基本上转移到辅助表中。

谢谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您要对MySQL而不是SQL Server使用触发器语法。像这样:

DELIMITER $$

CREATE TRIGGER MODIFIEDHWL ON HOURLYWORKLOG AFTER INSERT
    FOR EACH ROW AS
BEGIN
    INSERT INTO MODIFIEDHOURLYWORKLOG(EMPLOYEEREF, ORDERREF, HOURSWORKED, TOTALPAY, NOTES)
        SELECT NEW.EMPLOYEEREF, NEW.ORDERREF, NEW.HOURSWORKED, NEW.TOTALPAY, NEW.NOTES
        FROM DUAL
        WHERE NOT NEW.HOURSWORKED <=> OLD.HOURSWORKED;
END;$$

DELIMITER ;

答案 1 :(得分:0)

CREATE TRIGGER MODIFIEDHWL ON HOURLYWORKLOG
after update
for each row
AS
BEGIN
INSERT INTO MODIFIEDHOURLYWORKLOG
(EMPLOYEEREF, ORDERREF, HOURSWORKED, TOTALPAY, NOTES)
SELECT NEW.EMPLOYEEREF, NEW.ORDERREF, NEW.HOURSWORKED, NEW.TOTALPAY, 
NEW.NOTES
from dual where NEW.HOURSWORKED != OLD.HOURSWORKED
END;
/