How to fix this MySQL trigger?

前端 未结 2 1294
温柔的废话
温柔的废话 2021-01-26 00:37

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         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-26 01:22

    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.

提交回复
热议问题