mysql创建存储过程实现取款业务,需要向 transInfo 表添加一条记录,并修改 cardInfo 表中对应账号的余额。
时间: 2024-03-16 19:43:36 浏览: 207
好的,下面是实现这个需求的 MySQL 存储过程:
```
DELIMITER //
CREATE PROCEDURE `withdraw`(IN `account` VARCHAR(20), IN `amount` DECIMAL(10,2))
BEGIN
DECLARE `balance` DECIMAL(10,2);
DECLARE `trans_id` INT;
START TRANSACTION;
SELECT `balance` INTO `balance` FROM `cardInfo` WHERE `cardNo` = `account` FOR UPDATE;
IF `balance` >= `amount` THEN
UPDATE `cardInfo` SET `balance` = `balance` - `amount` WHERE `cardNo` = `account`;
INSERT INTO `transInfo` (`cardNo`, `transDate`, `transType`, `amount`) VALUES (`account`, NOW(), 'withdraw', `amount`);
SET `trans_id` = LAST_INSERT_ID();
COMMIT;
SELECT CONCAT('Withdrawal of ', `amount`, ' successful. Transaction ID is ', `trans_id`, ', Remaining balance is ', `balance` - `amount`, '.') AS `result`;
ELSE
ROLLBACK;
SELECT 'Insufficient balance.' AS `result`;
END IF;
END //
DELIMITER ;
```
这个存储过程名为 `withdraw`,接受两个参数:`account` 为账户号码,`amount` 为取款金额。它会检查账户余额是否足够,如果足够,则会向 `transInfo` 表中插入一条记录,并更新 `cardInfo` 表中对应账号的余额;否则会回滚事务。
可以通过以下语句调用这个存储过程:
```
CALL withdraw('1234567890', 100);
```
其中,`1234567890` 为账户号码,`100` 为取款金额。存储过程会返回一个值,表示操作的结果。
阅读全文