Prøv
CREATE TRIGGER NewTrigger
AFTER INSERT ON Transactions
FOR EACH ROW
UPDATE Accounts a
SET a.AccountBalance =
(SELECT SUM(TransactionAmount)
FROM Transactions
WHERE AccountID = a.AccountID)
WHERE a.AccountID = NEW.AccountID;
Her er SQLFiddle demo.
OPDATERING :Da udløsere ikke er tilgængelige for dig, prøv at wrap INSERT
og UPDATE
ind i en lagret procedure som denne
DELIMITER $$
CREATE PROCEDURE AddTransaction(IN aid INT, amount DECIMAL(11, 2))
BEGIN
START TRANSACTION;
INSERT INTO Transactions (AccountID, TransactionAmount)
VALUES (aid, amount);
UPDATE Accounts a
SET a.AccountBalance =
(SELECT SUM(TransactionAmount)
FROM Transactions
WHERE AccountID = a.AccountID)
WHERE a.AccountID = aid;
COMMIT;
END $$
DELIMITER ;
Og brug det derefter
CALL AddTransaction(1, 10.50);
Her er SQLFiddle demo for det scenarie.