begin declare @total float select @total=remain from card1 where cardid=@outcount
if @total>=@amount begin update card1 set remain=remain-@amount where cardid=@outcount update card1 set remain=remain+@amount where cardid=@incount end
end insert card1 values(1,1000.0) insert card1 values(2,500.0) exec mypro1 2,1,200 select * from card1 sp_help stu create procedure mypo2()
as insert into stu(sno,sname) values('95051','小明') go exec mypo2 select * from stu create table card2(cardid int,remain float)
drop procedure mypro2 create procedure mypro2 @outid int, @inid int, @money float as begin declare @total float select @total=remain from card2 where cardid=@outid begin transaction t1--设回滚点 if @total>@money begin
update card2 set remain=remain-@money where cardid=@outid
update card2 set remain=remain+@money where cardid=@inid print'转账成功' commit transaction t1--提交事务
end else begin print '转账失败'
rollback transaction t1--回滚 end
end
insert card2 values(1,1000.0) insert card2 values(2,1000.0) exec mypro2 2,1,1689 select * from card2 [其他解释] 使用事务。 begin transaction 数据操作 If @errno>0 rollback TransAction else Commit TransAction
set XACT_ABORT on begin tran --你的SQL语句例如如下id为主键 insert into tra(id,name) select '3','r3' insert into tra(id,name) select '3','r3' commit
[其他解释] 希望可以帮到你:代码如下
create table 自动转账机 ( 卡号 varchar(19) primary key, 金额 money check(金额>=0) ) insert into 自动转账机 values('6222023100051898533',120.00) insert into 自动转账机 values('6222023100051898573',0.00)
create table 自动取款机 ( 卡号 varchar(19) primary key, 金额 money check(金额>=100) ) insert into 自动取款机 values('6222023100051898533',120.00) insert into 自动取款机 values('6222023100051898573',0.00)
--转账 余额不足 数据回滚 转账失败 begin try begin tran update 自动转账机 set 金额 = 金额+500 where 卡号 = '6220203200051898533' update 自动转账机 set 金额 = 金额-500 where 卡号 = '6220203200051898573' commit tran --执行成功 end try begin catch rollback tran--余额不足 数据回滚 end catch
--取款 余额不足 数据回滚 begin try begin tran update 自动取款机 set 金额 = 金额-500 where 卡号 = '6220203200051898573' commit tran --执行成功 end try begin catch rollback tran--余额不足 数据回滚 end catch