触发器:使用Condition语句

时间:2014-09-30 16:35:07

标签: mysql sql if-statement triggers sql-insert

请查看以下查询

DELIMITER $$
CREATE TRIGGER `Ongoing_Portfolio_AINS` AFTER INSERT ON `Ongoing_Portfolio` FOR EACH ROW
BEGIN
    UPDATE Portfolio
    SET Invest_Amount = New.Investment_Value,
    Cash_Value = New.Cash_Value,
    Date_Of_Last_Update = New.Updated_Date
    WHERE idPortfolio = New.idPortfolio;

    INSERT INTO Ongoing_Fees (currentDate, Ongoing_Gross_Fee,Ongoing_Vat, Updated_Date, idPortfolio)
    SELECT current_timestamp,
    (New.Investment_Value+New.Cash_Value)*(p.Ongoing_Gross_Fee/100),
    (((New.Investment_Value+New.Cash_Value)*(p.Ongoing_Gross_Fee/100))*(p.Ongoing_eee_Fee/100))*0.2,
    New.Updated_Date,
    New.idPortfolio
    FROM Portfolio p
    WHERE p.idPortfolio = New.idPortfolio;
END;

但是在此处,Ongoing_Vat仅适用于p.Vat = true,否则为NULL。如何添加此条件语句以便正确计算Ongoing_Vat

1 个答案:

答案 0 :(得分:2)

归功于@ T​​welfth在评论中的回答,在代码中格式化,如下所示:

INSERT INTO Ongoing_Fees (currentDate, Ongoing_Gross_Fee,Ongoing_Vat, Updated_Date, idPortfolio)
SELECT 
  current_timestamp as currentDate,
  (New.Investment_Value+New.Cash_Value)*(p.Ongoing_Gross_Fee/100) as Ongoing_Gross_Fee,
  case when p.vat = true then (((New.Investment_Value+New.Cash_Value)*(p.Ongoing_Gross_Fee/100))*(p.Ongoing_eee_Fee/100))*0.2 
    else null end as Ongoing_Vat,
  New.Updated_Date as Updated_Date,
  New.idPortfolio as idPortfolio
FROM 
  Portfolio p
WHERE 
  p.idPortfolio = New.idPortfolio;