事务简析
事務(Transaction)是使用者定義的一個資料庫操作序列,這些操作要麼全做要麼全不做,是一個不可分割的工作單位。如果某一事務成功,則在該事務中進行的所有資料更改均會提交,成為資料庫中的永久組成部分。如果事務遇到錯誤且必須取消或回滾,則所有資料更改均被清除,主要用來保持資料的完整性、一致性。
虽然数据库的大部分操作都是生成日志的,管理员身份可以通过日志将数据回滚,但是这种操作太过于麻烦,并且无法精确恢复数据。
例如:
用户A在下午4点10分误操作删除了一笔数据
用户B在下午4点11分正常作业插入一笔数据
此时通过日主的数据恢复操作,很难精确恢复用户A的删除数据的同时保留用户B添加的数据!
此时就需要用到事务!
事务使用
基础的事务语句为:begin tran…commit tran
扩展为:
create table Student(PKID int IDENTITY(1,1) NOT NULL,Name nvarchar(50) not null,Age int)
set xact_abort on
begin transaction
insert into Student values('张三',10)
insert into Student values('李四',12)
if(@@error!=0)
rollback transaction
else
commit transaction
各语句、关键字含义
- set xact_abort on
将xact_abort置为on,当事务发生错误时会回滚事务中的所有事件! - begin transaction
开始事务的使用。 - rollback transaction
回滚事务。
特别提醒:rollback 只能回滚上次commit 或rollback 以来的事务。 - commit transaction
提交事务,即:将事务中的数据库操作更改保存生效。 - @@error
表示错误数,它并不能当做一个计数器来使用,因为它也是动态的!!! - savepoint
记录事务的状态点,可以将事务回滚至特定的点,而不是回滚整个事务。 - @@trancount
rollback tran會將@@trancount重置為0
begin tran會將@@trancount加1
commit tran會將@@trancount減1
所以事务的写法可以如下:
create table Student(PKID int IDENTITY(1,1) NOT NULL,Name nvarchar(50) not null,Age int)
set xact_abort on
begin transaction
insert into Student values(null,10)
insert into Student values('李四',12)
if(@@trancount=0)
rollback transaction
else
commit transaction
注:@@trancount常用于嵌套事务中,在此不作扩展,以后有机会再一起学习!
回滚扩展
除了事务的使用,还可以使用编程中常用的try … catch来进行配合事务进行异常捕捉处理。
create table Student(PKID int IDENTITY(1,1) NOT NULL,Name nvarchar(50) not null,Age int)
begin transaction
begin try
insert into Student values(null,10)
insert into Student values('李四',12)
end try
begin catch
if @@trancount > 0
rollback transaction
end catch
if @@trancount > 0
commit transaction
go