Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 17th, 2012  |  syntax: None  |  size: 1.03 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to fix this MySQL trigger?
  2. CREATE TRIGGER Transaction_insert BEFORE INSERT ON Transaction
  3. FOR EACH ROW WHERE Number = NEW.AccountNumber
  4. IF Account.CreditBalance + NEW.Amount < Account.CreditLimit THEN
  5. UPDATE Account SET CreditBalance = CreditBalance + NEW.Amount where Number = NEW.AccountNumber;
  6. ELSE
  7. SET NEW.Valid = 0
  8. END IF;
  9.        
  10. IF EXISTS (SELECT * FROM `Account` A
  11.             WHERE A.CreditBalance + NEW.Amount < A.CreditLimit AND
  12.                    A.Number = NEW.AccountNumber) THEN
  13.    UPDATE ...
  14.        
  15. DELIMITER //
  16.  
  17. -- Assumptions:
  18. --   1. Transaction.AccountNumber is F.K. REFERENCES Account(Number)
  19. --   2. Account.Number is UNIQUE
  20. --
  21. CREATE TRIGGER trg_bi_transaction BEFORE INSERT ON Transaction
  22. FOR EACH ROW
  23. BEGIN
  24.   -- Adjust account balance (if permitted)
  25.   --
  26.   UPDATE Account
  27.      SET CreditBalance = CreditBalance + NEW.Amount
  28.    WHERE Number = NEW.AccountNumber
  29.          AND
  30.          (CreditBalance + NEW.Amount) < CreditLimit;
  31.  
  32.   -- Was the adjustment valid/permitted?
  33.   --
  34.   SET NEW.Valid = (ROW_COUNT() = 1);
  35. END //
  36.  
  37. DELIMITER ;