2014-09-30 81 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