How to fix this MySQL trigger?

前端 未结 2 1304
温柔的废话
温柔的废话 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:12

    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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题