使用事务编程存储过程p_trans(),用于在不同账户之间完成转账。 转账是银行领域中常见的一种业务操作,可以定义一个账户表来存储账号信息。创建表的语句如下。 CREATE TABLE account ( id INT AUTO_INCREMENT PRIMARY KEY, #自动增长 account_name VARCHAR(11) NOT NULL, balance DECIMAL(10,1) UNSIGNED NOT NULL #不能取负值 ); INSERT INTO account VALUES(NULL,'a',100),(NULL,'b',100); 调用该存储过程,转账50;再次调用该存储过程,转账51。
时间: 2024-03-09 10:50:20 浏览: 167
好的,以下是使用事务编写的存储过程p_trans()的MySQL代码:
```
DELIMITER //
CREATE PROCEDURE p_trans(IN from_account_name VARCHAR(11), IN to_account_name VARCHAR(11), IN trans_amount DECIMAL(10, 1))
BEGIN
DECLARE from_account_id INT;
DECLARE to_account_id INT;
DECLARE from_account_balance DECIMAL(10, 1);
DECLARE to_account_balance DECIMAL(10, 1);
SELECT id, balance INTO from_account_id, from_account_balance FROM account WHERE account_name = from_account_name;
SELECT id, balance INTO to_account_id, to_account_balance FROM account WHERE account_name = to_account_name;
IF from_account_balance >= trans_amount THEN
START TRANSACTION;
UPDATE account SET balance = from_account_balance - trans_amount WHERE id = from_account_id;
UPDATE account SET balance = to_account_balance + trans_amount WHERE id = to_account_id;
COMMIT;
SELECT CONCAT('Transfer successful: ', trans_amount, ' yuan transferred from ', from_account_name, ' to ', to_account_name) AS result;
ELSE
SELECT 'Transfer failed: not enough balance' AS result;
END IF;
END //
DELIMITER ;
```
以上代码中,我们创建了一个名为p_trans的存储过程,该过程接收三个参数:from_account_name、to_account_name和trans_amount,代表转出账号、转入账号和转账金额。该存储过程会首先查询转出账号和转入账号的余额,如果转出账号余额足够,则进行转账操作并提交事务,并返回转账成功的信息;否则回滚事务并返回转账失败的信息。
接下来,我们可以通过以下代码调用该存储过程,完成转账50元的操作:
```
CALL p_trans('a', 'b', 50);
```
调用该存储过程后,如果转账成功,将会返回如下信息:
```
+--------------------------------------------+
| result |
+--------------------------------------------+
| Transfer successful: 50.0 yuan transferred from a to b |
+--------------------------------------------+
```
如果转账失败,则会返回如下信息:
```
+---------------------------+
| result |
+---------------------------+
| Transfer failed: not enough balance |
+---------------------------+
```
完成第一次转账后,我们可以再次调用该存储过程,完成转账51元的操作:
```
CALL p_trans('a', 'b', 51);
```
调用该存储过程后,由于转出账号a的余额不足,因此会返回转账失败的信息:
```
+---------------------------+
| result |
+---------------------------+
| Transfer failed: not enough balance |
+---------------------------+
```
希望这个回答对您有所帮助!
阅读全文