我的TRIGGER SQL语句有什么问题-MySQL

时间:2019-04-09 10:45:57

标签: mysql sql

我想跟踪特定表中的记录,然后再删除它们。我正在使用MySQL运行SQL TRIGGER语句,并且该语句成功运行,但是删除的行没有插入到表中。

CREATE TABLE `history_tblvendorpayment` LIKE `tblvendorpayment`;

ALTER TABLE `history_tblvendorpayment`
MODIFY COLUMN `id` INT UNSIGNED NOT NULL;

ALTER TABLE `history_tblvendorpayment` DROP PRIMARY KEY;

ALTER TABLE `history_tblvendorpayment`
ADD COLUMN `history_id` INT UNSIGNED NOT NULL;

ALTER TABLE `history_tblvendorpayment`
ADD CONSTRAINT PRIMARY KEY (`history_id`);

ALTER TABLE `history_tblvendorpayment`
MODIFY `history_id` INT UNSIGNED NOT NULL AUTO_INCREMENT;

DELIMITER $$

DROP TRIGGER `delete_tblvendorpayment`$$

CREATE TRIGGER `delete_tblvendorpayment` BEFORE DELETE on `tblvendorpayment`
FOR EACH ROW
BEGIN
    INSERT INTO history_tblvendorpayment (id, created_by,
    vendor_id, amount_payable,
    amount_payed, description,
    depositor_name, gl_code_credit,
    gl_code_debit, txn_date,
    pay_date, ref_id,
    bank, currency,
    date, md_approval,
    status, sage_status,
    memo_id)  
    VALUES (
        OLD.id, OLD.created_by,
        OLD.vendor_id, OLD.amount_payable,
        OLD.amount_payed, OLD.description,
        OLD.depositor_name, OLD.gl_code_credit,
        OLD.gl_code_debit, OLD.txn_date,
        OLD.pay_date, OLD.ref_id,
        OLD.bank, OLD.currency,
        OLD.date, OLD.md_approval,
        OLD.status, OLD.sage_status,
        OLD.memo_id
    );END$$

DELIMITER ;

1 个答案:

答案 0 :(得分:1)

然后尝试此方法尽管您的代码看起来不错,但这要短一些

CREATE TABLE `history_tblvendorpayment` LIKE `tblvendorpayment`;

ALTER TABLE `history_tblvendorpayment`
MODIFY COLUMN `id` INT UNSIGNED NOT NULL;

ALTER TABLE `history_tblvendorpayment` DROP PRIMARY KEY;

DELIMITER $$

CREATE TRIGGER `delete_tblvendorpayment` BEFORE DELETE on `tblvendorpayment`
FOR EACH ROW
BEGIN
    INSERT INTO history_tblvendorpayment
    SELECT *
    FROM tblvendorpayment
    WHERE id = OLD.id;
END$$

DELIMITER ;