【问题标题】:Triggers: Using Condition statements触发器:使用条件语句
【发布时间】:2014-09-30 16:35:07
【问题描述】:

请看下面的查询

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

【问题讨论】:

  • 当 p.vat = true 时的情况,然后是正在进行的_vat,否则 null 结束?
  • @paqogomez:如何添加条件语句?
  • 啊,是的,ty @paqogomez...没有足够的注意力来解决这个问题。愚蠢的工作。哈
  • @Twelfth,这意味着你是一个比我更好的员工。 :D
  • 我试图让我的工作与堆栈溢出时间的比率为:select sum(workhours) / sum(workhours) - sum(hoursonstack) ...愚蠢的事情给了我一个除以 0 错误

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


【解决方案1】:

感谢@Twelfth 在 cmets 中的回答,代码格式如下:

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;

【讨论】: