在插入触发器内部后更新同一行

时间:2017-11-04 07:11:55

标签: mysql sql database triggers

我必须使用一个触发器来更新插入的行。以下是我的触发器。

DELIMITER $$

USE `kikan_db`$$

CREATE TRIGGER `t_trigger` AFTER INSERT ON `t_order` 
FOR EACH ROW BEGIN
Declare kb_rate int;
Declare kb_amount int;

REPLACE INTO t_order_sales_month 
    SET order_no = NEW.order_no,
           search_sales_month = getSalesMonth(NEW.order_no);

SELECT kickback_rate INTO kb_rate from m_customer where customer_code = New.bill_customer_code;     
    SET kb_amount := 9999 / kb_rate;

 UPDATE `t_order`  SET `t_order`.kickback_amount = kb_amount where `t_order`.order_no = NEW.order_no;


END;
$$

DELIMITER ;

更新时收到错误。

我必须使用AFTER代替BEFORE类型的触发器

1 个答案:

答案 0 :(得分:0)

您可以更改after insert/update上虚拟new行的值,而不是仅使用before insert/update触发器,而不是{1}}:

Declare kb_rate int;
Declare kb_amount int;

SELECT kickback_rate INTO kb_rate from m_customer 
     where customer_code = New.bill_customer_code;     
SET kb_amount := 9999 / kb_rate;


SET new.kickback_amount = kb_amount;

(2)并在after insert/update触发器中执行其他SQL语句:

REPLACE INTO t_order_sales_month 
   SET order_no = NEW.order_no,
   search_sales_month = getSalesMonth(NEW.order_no);