Zkuste
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;
Zde je SQLFiddle demo.
AKTUALIZACE :Protože spouštěče nejsou dostupné, zkuste zabalit INSERT
a UPDATE
do uložené procedury, jako je tato
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 ;
A pak to použijte
CALL AddTransaction(1, 10.50);
Zde je SQLFiddle demo pro tento scénář.