我有一个复杂的MySQL触发器,我想简化一下。以下是触发器。
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, Gross_Fee, Insurance_Fee, Submit_Fee)
SELECT current_timestamp,
New.Gross_Fee,
(New.Gross_Fee)*(p.E_Fee/100),
((New.Gross_Fee)*(p.E_Fee/100))-(p.s_Fee/100)
FROM Portfolio p
WHERE p.idPortfolio = New.idPortfolio;
END;
你在这里看到的仅仅是一部分,还有更多。
你可以看到像
这样的行(New.Gross_Fee)*(p.i_Fee/100)
((New.Gross_Fee)*(p.i_Fee/100))-(p.s/100)
实际上,
Insurance_Fee
- 是New.Gross_Fee
Submit_Fee
- Insurance_Fee- (p.s_Fee/100)
我想为此目的引入变量,而不是编写这些长计算。因此变量将类似于
_InsuranceFee := (New.Gross_Fee)*(p.i_Fee/100)
_SubmitFee := _InsuranceFee - (p.s_Fee/100)
这种工作会缩短计算时间,当然也很容易阅读。但是,正如你所看到的,我的"插入"查询实际上是使用Select
查询。这是因为所有"百分比"值来自表Portfolio
(别名p
)那么如何在Select
查询内部为变量分配值并直接将它们插入到数据库中?
或者,还有其他任何方式将值赋给变量,所以我可以在select查询中使用变量吗?
答案 0 :(得分:0)
您是否尝试过使用局部变量?
declare `_InsuranceFee`, `_SubmitFee` decimal(10, 4);
INSERT INTO Ongoing_Fees (currentDate, Gross_Fee, Insurance_Fee, Submit_Fee)
SELECT current_timestamp, New.Gross_Fee,
`_InsuranceFee` := (New.Gross_Fee)*(p.E_Fee/100),
`_SubmitFee` := ((New.Gross_Fee)*(p.E_Fee/100))-(p.s_Fee/100)
FROM Portfolio p
WHERE p.idPortfolio = New.idPortfolio;