I am trying to update TableTwo using a DataTable built using TableOne.
The relationship between tables is a foreign column called TableOneId inside TableTwo.
I used the following code sample to make this work: Performing Batch Operations Using DataAdapters (MSDN)
The DataTable is populated in another Public Shared function.
I can’t figure out what is wrong. No error messages are reported. The watch reveals that the DataTable is loaded with data.
The DataTable is defined as:
Public MyDataTable As New DataTable
Public Shared Sub DefineDataTable()
Dim ErrorEmail As New ErrorEmailMessageClass
With ErrorEmail
Try
Using connection As New SqlConnection(My.Settings.MyDB)
MyDataTable.Columns.Add("ID", Type.GetType("System.Int32"))
MyDataTable.Columns.Add("Column1", Type.GetType("System.Int32"))
MyDataTable.Columns.Add("Column2", Type.GetType("System.Int32"))
MyDataTable.Columns.Add("Column3", Type.GetType("System.Int32"))
MyDataTable.Columns.Add("Column4", Type.GetType("System.Int32"))
End Using
Catch ex As Exception
.WriteError("Sub DefineDataTable", ex.Message)
End Try
End With
End Sub
But the SqlDataAdapter is not updating:
Public Shared Sub UpdateTable()
Dim ErrorEmail As New ErrorEmailMessageClass
With ErrorEmail
Try
Using connection As New SqlConnection(My.Settings.MyDB)
connection.Open()
Dim adapter As New SqlDataAdapter()
'Set the UPDATE command and parameters.
adapter.UpdateCommand = New SqlCommand( _
"UPDATE Schema.TableTwo " _
& "SET " _
& "Column1=@Column1, " _
& "Column2=@Column2, " _
& "Column3=@Column3, " _
& "Column4=@Column4 " _
& "WHERE TableOneId=@ID;", connection)
adapter.UpdateCommand.Parameters.Add("@Column1", SqlDbType.Int, 4, "Column1")
adapter.UpdateCommand.Parameters.Add("@Column2", SqlDbType.Int, 4, "Column2")
adapter.UpdateCommand.Parameters.Add("@Column3", SqlDbType.Int, 4, "Column3")
adapter.UpdateCommand.Parameters.Add("@Column4", SqlDbType.Int, 4, "Column4")
adapter.UpdateCommand.Parameters.Add("@ID", SqlDbType.Int, 4, "ID")
adapter.UpdateCommand.UpdatedRowSource = UpdateRowSource.OutputParameters
' Set the batch size.
adapter.UpdateBatchSize = 0
' Execute the update.
adapter.Update(MyDataTable)
connection.Close()
End Using
Catch ex As Exception
.WriteError("Sub UpdateTable", ex.Message)
End Try
End With
End Sub
As you’ve commented in your other question, here is my answer:
You should set the UpdateBatchSize property of the SqlDataAdapter to 0 (unlimited).
I don’t see a way to update table2 without looping table1.
Here is a sample code to show you one way to achieve this: