我故意在下面的代码中触发以下插入语句中的SqlException
,并将ModifiedBy
替换为正确的列名ModifiedB
答案 0 :(得分:2)
您需要在事务中包装整个SQL代码。举个例子:
create table errTest
(
intVal int
)
insert into errTest select 1
insert into errTest select 1/0
select * from errTest --one record
第二个插入失败,但由于没有显式启动任何事务,因此每个插入本身就是它自己的事务。第一个成功,第二个失败,表最终保留成功的插入。
如果所有插入都包含在事务中,并且xact_abort
处于打开状态,则任何插入引发的任何错误都将导致整个事务回滚:
create table errTest
(
intVal int
)
set xact_abort on
begin transaction
insert into errTest select 1
insert into errTest select 1/0
commit transaction
select * from errTest --zero records
答案 1 :(得分:0)
您需要将您的事务和连接传递给您希望在SQL事务中使用的所有命令,这是我的示例(我使用记事本删除了一些内容,因此它可能会在工作室中出错)
Private Sub main()
Using sql_conn
sql_conn.Open()
Dim SQL_transaction_INPUT As SqlClient.SqlTransaction = sql_conn.BeginTransaction
Try
Dim isOK as Boolean = False
isOK = update_BSE(myID, sql_conn, SQL_transaction_INPUT)
If isOK Then
SQL_transaction_INPUT.Commit()
sql_conn.Close()
Else
SQL_transaction_INPUT.Rollback()
sql_conn.Close()
End If
Catch ex As Exception
SQL_transaction_INPUT.Rollback()
If sql_conn.State = ConnectionState.Open Then sql_conn.Close()
End Try
End Using
End Sub
Private Function update_BSE(ByVal _IDmod As Integer, _
ByVal conn_with_trans As SqlConnection, _
ByVal conn_transaction As SqlTransaction) As Boolean
Dim ins As String = "UPDATE something WHERE IDrec = @IDmod"
Dim cmdINS As New SqlCommand(ins, conn_with_trans, conn_transaction)
Try
With cmdINS.Parameters
.Add("IDmod", SqlDbType.Int).Value = _IDmod
End With
cmdINS.ExecuteNonQuery()
Return True
Catch ex As Exception
Return False
End Try
End Function