一直以为存储过程会自动实现事务操作,其实不然。存储过程只是提供的事务操作的支持。要实现事务操作,还得自己实现。 

       基本上方法有两个:

  •       SET XACT_ABORT


指定当 Transact-SQL 语句产生运行时错误时,Microsoft® SQL Server™ 是否自动回滚当前事务。

 

语法
SET XACT_ABORT { ON | OFF }

注释
       当 SET XACT_ABORT 为 ON 时,如果 Transact-SQL 语句产生运行     时 错误,整个事务将终止并回滚。为 OFF 时,只回滚产生错误的 Transact-SQL 语句,而事务将继续进行处理。编译错误(如语法错误)不受 SET XACT_ABORT 的影响。

对于大多数 OLE DB 提供程序(包括 SQL Server),隐性或显式事务中的数据修改语句必须将 XACT_ABORT 设置为 ON。唯一不需要该选项的情况是提供程序支持嵌套事务时。有关更多信息,请参见分布式查询和分布式事务。

SET XACT_ABORT 的设置是在执行或运行时设置,而不是在分析时设置。

  

  

 例:

      

存储过程中的事务实现create proc testproc
存储过程中的事务实现
as
存储过程中的事务实现
SET XACT_ABORT on
存储过程中的事务实现
begin tran
存储过程中的事务实现
insert into tableA (field1) values ('aa')
存储过程中的事务实现
insert into tableB (field1) values ('bb')
存储过程中的事务实现
commit tran
存储过程中的事务实现
SET XACT_ABORT off
存储过程中的事务实现

 

  • begin tran

         /*要实现的操作*/
       commit tran
       if @@error>0
       rollback

 

     例:

    

存储过程中的事务实现  create proc testproc
存储过程中的事务实现      
as
存储过程中的事务实现
存储过程中的事务实现      
begin tran
存储过程中的事务实现     
insert into tableA (field1) values ('aa')
存储过程中的事务实现     
insert into tableB (field1) values ('bb')
存储过程中的事务实现     
commit tran
存储过程中的事务实现     
if @@error>0
存储过程中的事务实现      
rollback
存储过程中的事务实现
存储过程中的事务实现


另外,在.NET的ADO.NET数据库编程中,可以使用SqlTransaction实现事务操作。

   例:

   



相关文章:

  • 2022-12-23
  • 2021-07-26
  • 2022-12-23
  • 2022-02-11
  • 2022-02-25
  • 2021-09-19
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-22
相关资源
相似解决方案