存储过程中的事务实现
⼀直以为存储过程会⾃动实现事务操作,其实不然。存储过程只是提供的事务操作的⽀持。要实现事务操作,还得⾃⼰实现。
基本上⽅法有两个:
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
sqltransaction什么意思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
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论