视频链接:
【例6-2】假设银行存在两个借记卡账户(account)李三与‘王五,要求这两个借记卡账户不能用于透支,即两个账户的余额 (balance) 不能小于0。创建存储过程tran procO, 实现两个账户的转账业务。
首先,创建account表
其次,向其插入两条记录
最后,创建存储过程,实现转账过程
delimiter@@
create procedure transfer_proc(in from_account int,in to_account int,in money int)
modifies sql data
begin
declare continue handler for 1690#负责处理Mysql错误代码1690,当发生错误时,执行回滚操作;
begin
SELECT '余额小于0' 信息;
rollback;
end;
start transaction;#负责开启事务,并隐式的关闭自动提交
update account set balance=balance+money where account_no=to_account;
update account set balance=balance-money where account_no=from_account;
commit;
end@@
delimiter ;
call transfer_proc1(1,2,800);
select *from account;
call transfer_proc1(1,2,800);
SELECT*FROM account;
【例6-3】示例。下面创建的两个存储过程,分别对在同一个事务中创建两个账号相同的银行账户进行的不同处理。
PROCEDURE save_p1_proc()
DELIMITER@@
CREATE PROCEDURE save_p1_proc()
BEGIN
DECLARE CONTINUE HANDLER FOR 1062
BEGIN
ROLLBACK TO b;#事务回滚到保存点b
END;
START TRANSACTION;
INSERT INTO account VALUES(NULL,'赵四',1000);
SAVEPOINT b;#设置保存点
#LAST_INSERT_ID()获取赵四账户的账号
INSERT INTO account VALUES(LAST_INSERT_ID(),'钱六',1000);
COMMIT;
END@@;
DELIMITER;
CALL save_p1_proc();
SELECT * FROM account;
DELETE FROM account WHERE account_no=3;
SELECT * FROM account;
PROCEDURE save_p2_proc()
DELIMITER@@
CREATE PROCEDURE save_p2_proc()
BEGIN
DECLARE CONTINUE HANDLER FOR 1062
BEGIN
ROLLBACK TO b;#事务回滚到保存点b
ROLLBACK;
END;
START TRANSACTION;
INSERT INTO account VALUES(NULL,'赵四',1000);
SAVEPOINT b;#设置保存点
#LAST_INSERT_ID()获取赵四账户的账号
INSERT INTO account VALUES(LAST_INSERT_ID(),'钱六',1000);
COMMIT;
END@@;
DELIMITER;
CALL save_p2_proc();
SELECT * FROM account;