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

       基本上方法有两个:

  •       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实现事务操作。

   例:

   

Public Sub RunSqlTransaction(myConnString As String)
    
Dim myConnection As New SqlConnection(myConnString)
    myConnection.Open()
    
    
Dim myCommand As SqlCommand = myConnection.CreateCommand()
    
Dim myTrans As SqlTransaction
    
    
' Start a local transaction
    myTrans = myConnection.BeginTransaction()
    
' Must assign both transaction object and connection
    ' to Command object for a pending local transaction
    myCommand.Connection = myConnection
    myCommand.Transaction 
= myTrans
    
    
Try
      myCommand.CommandText 
= "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
      myCommand.ExecuteNonQuery()
      myCommand.CommandText 
= "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
      myCommand.ExecuteNonQuery()
      myTrans.Commit()
      Console.
WriteLine("Both records are written to database.")
    
Catch e As Exception
      
Try
        myTrans.Rollback()
      
Catch ex As SqlException
        
If Not myTrans.Connection Is Nothing Then
          Console.
WriteLine("An exception of type " & ex.GetType().ToString() & _
                            
" was encountered while attempting to roll back the transaction.")
        
End If
      
End Try
    
      Console.
WriteLine("An exception of type " & e.GetType().ToString()   "was encountered while inserting the data.")
      Console.
WriteLine("Neither record was written to database.")
    
Finally
      myConnection.Close()
    
End Try
End Sub
 'RunSqlTransaction



 

posted on 2005-07-07 17:05  与雪共舞  阅读(12302)  评论(6编辑  收藏  举报