I’m developing a MySQL stored procedure for transferring money between accounts. The procedure is named execute_transfer, and it accepts parameters such as the transfer amount, a note, the account from which money will be deducted, and the account that will receive the funds.
The basic operation works well. For instance, when I call execute_transfer(75, 'payment', 5, 10), it correctly transfers 75 dollars from account 5 to account 10.
However, I’m running into two significant problems:
- The procedure permits transfers even if one or both accounts don’t exist.
- It doesn’t verify whether sufficient funds are available in the sending account before processing the transfer.
As an example, executing execute_transfer(500000, 'test transfer', 20, 30) goes through without errors, even if those account IDs are invalid.
Here’s what my tables look like:
CREATE TABLE accounts (
id INT AUTO_INCREMENT PRIMARY KEY,
balance DECIMAL(10,2) CHECK (balance >= 0)
);
CREATE TABLE transfers (
id INT AUTO_INCREMENT PRIMARY KEY,
amount DECIMAL(10,2),
from_account INT NOT NULL,
to_account INT NOT NULL,
note VARCHAR(100),
created_at DATETIME,
FOREIGN KEY (from_account) REFERENCES accounts(id),
FOREIGN KEY (to_account) REFERENCES accounts(id)
);
And here’s the stored procedure I’m using:
DELIMITER //
CREATE PROCEDURE execute_transfer(
IN transfer_amount DECIMAL(10,2),
IN note VARCHAR(100),
IN from_acc INT,
IN to_acc INT
)
BEGIN
START TRANSACTION;
UPDATE accounts
SET balance = balance - transfer_amount
WHERE id = from_acc;
UPDATE accounts
SET balance = balance + transfer_amount
WHERE id = to_acc;
INSERT INTO transfers (amount, from_account, to_account, note, created_at)
VALUES (transfer_amount, from_acc, to_acc, note, NOW());
COMMIT;
END //
DELIMITER ;
What is the best approach to implement checks for account validity and balance before completing the transfers?