SQL Server事务处理_Transaction

在SQL Server中打开:键入

----事务处理

----事务的分类
----1. 显式事务:使用begin tran明确指定事务开始,即关于事务的所有操作由用户使用代码自行控制
use CompanyDB
go
----创建表,模拟汇款转账
create table AccountInfo
(
AccountGUID int primary key identity,
AccountName nvarchar(20) not null,
AccountType nvarchar(20) not null,
AccountMoney money not null,
AccountState nvarchar(20) not null,
 constraint ck_AccountMoney CHECK(AccountMoney>0)
)
go

----插入相关测试数据
insert into AccountInfo(AccountName,AccountType,AccountMoney,AccountState)
     values('Eva','RMB',5000,'Active')
insert into AccountInfo(AccountName,AccountType,AccountMoney,AccountState)
     values('Eva','Dollor',1000,'Active')
    
----模拟汇款,跟新各个表中账户的情况
----先将人民币账户的存款扣除
update AccountInfo set AccountMoney=AccountMoney-5000
where AccountName='Eva' and AccountType='RMB'
----再向美元账户加上相应的存款(假设人民币与美元汇率为5:1)
update AccountInfo set AccountMoney=AccountMoney+5000/5
where AccountName='Eva' and AccountType='Dollor'

select * from dbo.AccountInfo


----事务处理
----先声明一个变量累计多条操作语句的总错误编号
declare @sumerror int
set @sumerror=0
----在进行操作前开启事务

begin transaction
----先将人民币账户的存款扣除
update AccountInfo set AccountMoney=AccountMoney-5000
where AccountName='Eva' and AccountType='RMB'
----每执行完一条语句就累计一次错误编号
set @sumerror=@sumerror+@@error
----再向美元账户加上相应的存款(假设人民币与美元汇率为5:1)
update AccountInfo set AccountMoney=AccountMoney+5000/5
where AccountName='Eva' and AccountType='Dollor'
----@@error系统全局变量,其作用是得到上一条SQL语句是否出现错误
set @sumerror=@sumerror+@@error

----待所有操作语句完成后查询累计错误编号值
if @sumerror=0
begin
----如果没有任何语句出现错误,则表示所有的操作语句都已正常执行完毕
----则进行事务提交
 commit transaction
end
else
begin
----反之进行事务回滚
 rollback transaction
end
go

----创建一张表进行事务保存点的演示
create TABLE TempTable
(
ID int primary key identity,
Info nvarchar(20) not null
)
go
----清空表数据
truncate table TempTable
select * from TempTable

----开始事务也可简写为以下代码
begin tran
insert into TempTable values('Info1')
----设置一号保存点
save tran p1
insert into TempTable values('Info2')
----设置二号保存点
save tran p2
insert into TempTable values('Info3')
----回滚至一号保存点位置
rollback tran p1
----提交当前事务

commit tran


----2. 隐式事务:通过使用设定语句set implicit_transactions on,将隐式事务模式打开
set implicit_transactions on
----在隐式事务提交模式下,在当前连接不存在事务时,任何一条增删改的语句都会自动开启事务,'
----但事务的回滚或提交由用户自己控制,控制的方式与显示事务提交模式一样,使用rollback或
----commit进行,至于如何确定当前连接状态中是否存在正在运行的事务,可用下面语句查看:

----查看是否有正在运行的事务

select @@trancount
----此全局变量的作用是查看当前连接状态下的事务总数,如果没有事务运行则返回结果为0,
----每运行一次begin transaction语句就会使此变量的值加1,每运行一次commit tran会使
----事务总数减1,但只要运行一次rollback tran,所有事务会回滚

posted @ 2011-05-17 11:18  eva.xiao  阅读(478)  评论(0编辑  收藏  举报