使用MySql根据账户表来创建存储过程,实现两个账户转账,转出账户A,转入账户B,转账前需要判断转账金额大于账户余额,转账成功后输入账户A和账户B的余额信息
时间: 2024-03-19 17:41:23 浏览: 110
好的,以下是针对您的问题编写的MySQL存储过程代码:
```
DELIMITER //
CREATE PROCEDURE transfer_money(IN accountA INT, IN accountB INT, IN amount DECIMAL(10,2))
BEGIN
DECLARE balanceA DECIMAL(10,2);
DECLARE balanceB DECIMAL(10,2);
-- 获取账户A和账户B的余额
SELECT balance INTO balanceA FROM account WHERE id = accountA;
SELECT balance INTO balanceB FROM account WHERE id = accountB;
-- 判断账户A的余额是否足够
IF balanceA < amount THEN
SELECT '转账失败,账户A余额不足' AS message;
ELSE
-- 开始转账
START TRANSACTION;
UPDATE account SET balance = balanceA - amount WHERE id = accountA;
UPDATE account SET balance = balanceB + amount WHERE id = accountB;
-- 获取转账后账户A和账户B的余额
SELECT balance INTO balanceA FROM account WHERE id = accountA;
SELECT balance INTO balanceB FROM account WHERE id = accountB;
-- 提交事务并输出转账成功信息及账户A和账户B的余额
COMMIT;
SELECT '转账成功' AS message, balanceA AS '账户A余额', balanceB AS '账户B余额';
END IF;
END //
DELIMITER ;
```
其中,`account`表是您存储账户信息的表,包含以下字段:
- `id`:账户ID
- `balance`:账户余额
在调用该存储过程时,需要传入以下参数:
- `accountA`:转出账户A的账户ID
- `accountB`:转入账户B的账户ID
- `amount`:转账金额
例如,调用语句可以是:
```
CALL transfer_money(1, 2, 100.00);
```
其中,`1`和`2`分别代表账户A和账户B的账户ID,`100.00`代表转账金额。调用成功后,将会输出转账成功或失败的信息,以及账户A和账户B的余额。
阅读全文