如何修复这个MySQL触发器?

时间:2011-12-06 08:41:18

标签: mysql database triggers

我正试图让这个触发器起作用:

CREATE TRIGGER Transaction_insert BEFORE INSERT ON Transaction
FOR EACH ROW WHERE Number = NEW.AccountNumber 
IF Account.CreditBalance + NEW.Amount < Account.CreditLimit THEN
UPDATE Account SET CreditBalance = CreditBalance + NEW.Amount where Number = NEW.AccountNumber;
ELSE
SET NEW.Valid = 0
END IF; 

这是我从myPHPAdmin获得的错误。

enter image description here

2 个答案:

答案 0 :(得分:0)

更新答案

这就是我认为你想要的,假设AccountTransactionNumber / AccountNumber上的1:N关系:

DELIMITER //

-- Assumptions:
--   1. Transaction.AccountNumber is F.K. REFERENCES Account(Number)
--   2. Account.Number is UNIQUE
--
CREATE TRIGGER trg_bi_transaction BEFORE INSERT ON Transaction
FOR EACH ROW
BEGIN
  -- Adjust account balance (if permitted)
  --
  UPDATE Account
     SET CreditBalance = CreditBalance + NEW.Amount
   WHERE Number = NEW.AccountNumber
         AND
         (CreditBalance + NEW.Amount) < CreditLimit;

  -- Was the adjustment valid/permitted?
  --
  SET NEW.Valid = (ROW_COUNT() = 1);
END //

DELIMITER ;

如果Account允许,该触发器将尝试为任何给定的Transaction更新正确的CreditLimit。如果UPDATE成功,Valid字段将设置为1,如果不成功则设置为0。

原始答案

MySQL触发器不支持触发级WHERE子句。在触发器主体内移动Number / NEW.AccountNumber检查。

答案 1 :(得分:0)

您的IF需要是一个完整的SELECT来引用另一个表(Account

IF EXISTS (SELECT * FROM `Account` A
            WHERE A.CreditBalance + NEW.Amount < A.CreditLimit AND 
                   A.Number = NEW.AccountNumber) THEN
   UPDATE ...

编辑:这是你的第二个重复答案

在这种情况下,请删除FOR FOR EACH ROW后的WHERE