1.什么是事务

【SQLServer系列教程】——事务详解

2.事务的特性

【SQLServer系列教程】——事务详解

3.事务的分类

【SQLServer系列教程】——事务详解

4.事务的创建

【SQLServer系列教程】——事务详解
【SQLServer系列教程】——事务详解

5.案例代码:

示例1:使用事务回滚有错误的数据

use StudentManager
go
declare @errorSum int --定义变量,用于累计事务执行过程中的错误
set @errorSum=0        --初始化为0,即无错误
begin transaction
   begin		
		update CardAccount set CurrentMoney=CurrentMoney-1000
					where StudentId=100001
       set @[email protected][email protected]@error --累计是否有错误		
		update CardAccount set CurrentMoney=CurrentMoney+1000
					where StudentId=100002
      set @[email protected][email protected]@error --累计是否有错误
      if(@errorSum>0)
			rollback transaction
      else 
          commit transaction
 end
go
--查询余额
select Students.StudentId,StudentName,CurrentMoney from Students
inner join CardAccount on Students.StudentId=CardAccount.StudentId

示例2:启用事务的存储过程

use StudentManager
go
if exists(select * from sysobjects where name='usp_TransferAccounts')
drop procedure usp_TransferAccounts
go
create procedure usp_TransferAccounts
@inputAccount int,--转入账户
@outputAccount int,--转出账户
@transferMoney int --交易金额
as
	declare @errorSum int 
	set @errorSum=0      
	begin transaction
	   begin		
			update CardAccount set [email protected]
						where [email protected]
			set @[email protected][email protected]@error 	
			update CardAccount set [email protected]
						where [email protected]
		   set @[email protected][email protected]@error 
		   if(@errorSum>0)
				rollback transaction
		   else 
				commit transaction
	 end	
go
--测试失败的转账
exec usp_TransferAccounts 100002,100001,1000
--查询余额
select Students.StudentId,StudentName,CurrentMoney from Students
inner join CardAccount on Students.StudentId=CardAccount.StudentId
--测试成功的转账
exec usp_TransferAccounts 100002,100001,800
--查询余额
select Students.StudentId,StudentName,CurrentMoney from Students
inner join CardAccount on Students.StudentId=CardAccount.StudentId

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-12
  • 2021-12-10
  • 2022-12-23
  • 2021-04-11
  • 2021-11-01
猜你喜欢
  • 2021-11-27
  • 2022-12-23
  • 2021-08-04
  • 2022-12-23
  • 2021-07-28
  • 2021-07-20
相关资源
相似解决方案