I am trying to make an exact copy from one sql table to another. Both tables reside in the same database. I am trying to use SqlBulkCopy but receive a "There is already an open DataReader associated with this Command which must be closed first." error.
I have found many similar problems and tried the solutions contained therein with no success. I am very new to this so any help with this (or any of the code below) is appreciated.
SqlCommand readLocal = new SqlCommand("Select CompanyNumber,CompanyName,AccessNumber,TruckName,TransferStartTime,TransferEndTime,TransferVolume FROM TransfersNew", conLocal);
try
{
conLocal.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conLocal))
{
bulkCopy.DestinationTableName = "dbo.TransfersHistory";
try
{
using (SqlDataReader readerLocal = readLocal.ExecuteReader())
{
while (readerLocal.Read())
{
bulkCopy.WriteToServer(readerLocal);
}
}
}
catch (Exception ex)
{
Globals.infoString = ex.Message;
Globals.infoStringColor = true;
var newForm = new pagePopupInfo();
newForm.ShowDialog();
}
finally
{
conLocal.Close();
}
}
}
catch (Exception ex)
{
Globals.infoString = ex.Message;
Globals.infoStringColor = true;
var newForm = new pagePopupInfo();
newForm.ShowDialog();
}
finally
{
conLocal.Close();
}
I'm wide open to suggestions. Thanks
Matheus' suggestion worked. My additional issue regarding not copying the data turned out to be that it was just not copying the first record. I changed my code to this to correct that issue:
try
{
conLocal.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conLocal))
{
bulkCopy.DestinationTableName = "dbo.TransfersHistory";
SqlDataReader readerLocal = readLocal.ExecuteReader();
bulkCopy.WriteToServer(readerLocal);
}
}