首页 > 解决方案 > 在同一个 ADO.NET ExecuteReader 调用中更新和选择

问题描述

我正在使用我继承的其他人的代码,我需要进行完整性检查。

在下面的 SQL 中似乎没有运行更新语句,只有选择语句。我想知道这是否与交易有关?我有类似的代码,我在其他地方写过,效果很好。并且在整个继承的代码中重复了相同的模式,因此它们都不应该工作,但它似乎以前工作过。

此代码的目的是从平面文件源中引入数据,对其进行清理,并最终将其放入具有适当数据类型的表中以进行报告。为了进行清理,它将它放在一个包含所有 varchar 列的临时表中。

无论如何,为什么这些更新语句没有任何效果?

Dim oConn As New SqlConnection(ProgConnString)
Dim oTrans As SqlTransaction
oConn.Open()
oTrans = oConn.BeginTransaction()

'Create the temp staging table
Dim strTempTableName As String = CreateTempTable(oConn, oTrans, oDataTable)

'Write the passed DataTable to the temp staging table
Dim copier As New SqlBulkCopy(oConn, SqlBulkCopyOptions.Default, oTrans)
copier.DestinationTableName = strTempTableName
copier.BulkCopyTimeout = 30
copier.WriteToServer(oDataTable)
copier.Close()

'This is the update statement that does not run
Dim strSQL As String = String.Empty
strSQL &= " UPDATE " & strTempTableName
strSQL &= " set [MyCol] = REPLACE([MyCol], '$', '') "
strSQL &= ", [MyCol2] = REPLACE([MyCol2], '$', '') "
strSQL &= ", [MyCol3] = REPLACE([MyCol3], '$', '') "

'[ some other update statements that also do not run... ]

' If I throw this in the mix, the update commands run
'Using oCmd1 As New SqlCommand(strSQL, oConn, oTrans)
'    oCmd1.ExecuteNonQuery()
'End Using
'strSQL = ""

'This is where we pull back the result. It should have all the above
' fixes from the update statements but it doesn't
strSQL &= " SELECT * FROM " & strTempTableName

Dim oCmd As New SqlCommand(strSQL, oConn, oTrans)
Dim oDataReader As SqlDataReader = oCmd.ExecuteReader
Dim resultDataTable As New DataTable
resultDataTable.Load(oDataReader)

'Drop temp table
strSQL = ""
strSQL &= vbNewLine & "IF OBJECT_ID('tempdb.." & strTempTableName & "') IS NOT NULL DROP TABLE " & strTempTableName
oCmd = New SqlCommand()
oCmd.Connection = oConn
oCmd.Transaction = oTrans
oCmd.CommandType = CommandType.Text
oCmd.CommandText = strSQL
oCmd.ExecuteNonQuery()

oTrans.Commit()

'Use the results
SomeFunctionWhatever(resultDataTable)

现在起作用的是,如果我ExecuteNonQuery()在选择之前将其拆分为一个。

是什么导致Update命令被忽略,是事务吗?您可以在同一个通话中执行Updateand ,对吗?SelectExecuteReader()

标签: vb.nettsqltransactionsado.net

解决方案


推荐阅读