gpt4 book ai didi

mysql - SQL 触发器 : Insert deleted row into a table at once without listing every column as INSERT values

转载 作者:行者123 更新时间:2023-11-29 05:49:35 25 4
gpt4 key购买 nike

我有一个已经可以使用的代码,但我正在寻找一种方法来编写一个 sql 语句,当从另一个表中删除一行时,该语句将插入到一个表中,而不必将每一列列为下面的值插入语句。对于一个表有很多列的情况,它真的会派上用场。这是我目前的代码,我希望有人能帮我修改它。

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 ;

我希望是这样的:

DELIMITER $$

DROP TRIGGER `delete_tblvendorpayment`$$

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

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

关于mysql - SQL 触发器 : Insert deleted row into a table at once without listing every column as INSERT values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55686619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com