ylbtech_sqlserver
create database bank go use bank go create table users ( uid int primary key identity(1,1), uname varchar(10) not null, balance float ) go insert into users values('zzl', 1000) insert into users values('zsy', 1000) select * from users --创建一个事物,实现zsy转账500给zzl /* update users set balance = balance + 500 where uname = 'zzl' update users set balance = balance - 500 where uname = 'zzz'*/ BEGIN TRANSACTION DECLARE @n1 int DECLARE @n2 int update users set balance = balance + 500 where uname = 'zzl' SET @n1 = @@ROWCOUNT update users set balance = balance - 500 where uname = 'zsy' SET @n2 = @@ROWCOUNT IF @n1 >= 1 and @n2 >= 1 BEGIN COMMIT PRINT '转账成功' END ELSE BEGIN ROLLBACK PRINT '转账失败!!' END select * from users --避免透支---------------------------------- BEGIN TRANSACTION DECLARE @n1 int DECLARE @n2 int DECLARE @bal float --保存班长支出以后的余额 update users set balance = balance + 500 where uname = 'zzl' SET @n1 = @@ROWCOUNT update users set balance = balance - 500 where uname = 'zsy' SET @n2 = @@ROWCOUNT IF @n1 >= 1 and @n2 >= 1 BEGIN /* COMMIT PRINT '转账成功' */ --如果zsy-500为负,就回滚事务 select @bal = balance from users where uname = 'zsy' IF @bal < 0 BEGIN PRINT '班长余额不足,转账失败' ROLLBACK END ELSE BEGIN PRINT '转账成功' COMMIT END END ELSE BEGIN ROLLBACK PRINT '转账失败!!' END select * from users
分类:
SQL Server
本文转自ylbtech博客园博客,原文链接:http://www.cnblogs.com/ylbtech/p/3828814.html
,如需转载请自行联系原作者