How to fix this MySQL trigger?

…衆ロ難τιáo~ 提交于 2019-12-20 05:42:36

问题


I'm trying to get this trigger to work:

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; 

This is the error I get from myPHPAdmin.


回答1:


Your IF needs to be a full SELECT to reference another table (Account)

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

Edit: this was on your 2nd duplicate answer

In this case, remove the WHERE after FOR EACH ROW




回答2:


Updated Answer

This is what I think you want, assuming that Account to Transaction is a 1:N relationship keyed on Number/AccountNumber:

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 ;

That trigger will attempt to UPDATE the proper Account for any given Transaction if the CreditLimit permits. The Valid field will be set to 1 if the UPDATE succeeded, and 0 if it did not.

Original Answer

MySQL triggers do not support trigger-level WHERE clauses. Move the Number/NEW.AccountNumber check inside the trigger body.



来源:https://stackoverflow.com/questions/8397172/how-to-fix-this-mysql-trigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!