2014-09-30 86 views
1

请看看下面的查询触发器:使用条件语句

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

情况下,当p.vat = true,那么ongoing_vat否则返回null结束了吗? – Twelfth 2014-09-30 16:42:23

+0

@paqogomez:我如何添加条件语句? – 2014-09-30 16:45:52

+0

@Telfelf:我不明白。你能否将这部分添加到我的代码中?我对SQL的东西有点新鲜。 – 2014-09-30 16:47:40

回答

2

感谢@第十二在评论的答案,在代码格式化它应该是这样的:

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; 
+0

谢谢。工作很好.. – 2014-10-01 07:28:43

+0

请在这里回答? - http://stackoverflow.com/questions/26294825/variable-is-getting-null-after-calculations-in-mysql-trigger – 2014-10-10 11:03:41