在触发器中使用If_Else时出错

时间:2014-09-21 14:24:00

标签: mysql sql database triggers insert

请参考下图

enter image description here

我想在After Insert表上创建一个Ongoing_Fees触发器,用于更新VAT表。但是,在将数据插入VAT表之前,应检查特定VAT的{​​{1}}字段是否为Portfoliotrue表对Ongoing_Fees表具有foreign key访问权限,因此可以访问相关的投资组合。

以下是我的尝试

Portfolio

但当然,它有一个错误

DELIMITER $$
CREATE TRIGGER `Ongoing_Fees_AINS` AFTER INSERT ON `Ongoing_Fees` FOR EACH ROW
BEGIN
DECLARE `vat` Boolean;
`vat` = SELECT VAT from Portfolio WHERE Portfolio.idPortfolio = New.idPortfolio;

IF (`vat` == true) THEN
    INSERT INTO VAT VALUES (100, current_Timestamp, New.idPortfolio, New.idOngoing_Fees)
END;

1 个答案:

答案 0 :(得分:2)

尝试:

DELIMITER $$

CREATE TRIGGER `Ongoing_Fees_AINS` AFTER INSERT ON `Ongoing_Fees`
FOR EACH ROW
BEGIN
  DECLARE `_vat` BOOL;
  SET `_vat` := (SELECT `VAT` FROM `Portfolio` WHERE `Portfolio`.`idPortfolio` = NEW.`idPortfolio`);    
  IF (`_vat` = TRUE) THEN
    INSERT INTO `VAT` (
         `Amount`,
         `current_timestamp`,
         `Portfolio_idPortfolio`,
         `Ongoing_Fees_idOngoing`
    )
    VALUES (
         100,
         CURRENT_TIMESTAMP(),
         NEW.`idPortfolio`,
         NEW.`idOngoing_Fees`
    );
  END IF;
END$$

DELIMITER ;

较短的版本:

DELIMITER $$

CREATE TRIGGER `Ongoing_Fees_AINS` AFTER INSERT ON `Ongoing_Fees`
FOR EACH ROW
BEGIN
    INSERT INTO `VAT` (
         `Amount`,
         `current_timestamp`,
         `Portfolio_idPortfolio`,
         `Ongoing_Fees_idOngoing`
    )
    SELECT
         100,
         CURRENT_TIMESTAMP(),
         NEW.`idPortfolio`,
         NEW.`idOngoing_Fees`
    FROM
         DUAL
    WHERE
         TRUE = (SELECT
                      `VAT`
                 FROM
                      `Portfolio`
                 WHERE
                      `Portfolio`.`idPortfolio` = NEW.`idPortfolio`
                );
END$$

DELIMITER ;