现在的位置: 首页 > 综合 > 正文

事务说明

2012年11月29日 ⁄ 综合 ⁄ 共 871字 ⁄ 字号 评论关闭
事务是一种机制,是一个操作序列,它包含了一组对数据库操作命令,所有的操作做为一个整体一起向系统提交或撤消操作请求,要么都执行,要么都不执行。

begin transaction来开始事务
commit transaction来结束事务

例子:
delare @transaction_name varchar(32)
select @transaction_name = 'my_transaction_delete'
begin transaction @transaction_name
go
use test
go
delete from department
where dept_id = '11'
go
delete from employee
where dept_id = '11'
go
commit transaction my_transaction_delete
go

事务回滚是指当事务中的某一语句执行失败时,将对数据库的操作恢复到事务执行前或某个指定位置。

使用rollback transaction语句

要让事务回滚到指定位置,则需要在事务中设定保存点(Save Point)。

使用save transaction语句

删除后勤部,再将后勤部的职工划分到经理室
begin transaction my_transaction_delete
use test
go
delete from department
where dept_name='1012'

save transaction after_delete  /*设置回滚保存点*/

update employee
set dept_id='1001'
where dept_id='1002'

if @@error!=0 or @@rowcount=0 then
begin
rollback tran after_delete  /*回滚到保存点after_delete,如果使用rollback tran my_transaction_delete,则会回到事务开始前*/
commit tran
print '更新员工信息时出错!'
return
end

commit my_transaction_delete
go

抱歉!评论已关闭.