Search code examples
c#datatablesqlbulkcopyidatareader

IDataReader vs DataTable; pros and cons


I am working on doing a large scale insert/update operation.

So I am using SqlBulkCopy.

SqlConnection myConnection = new SqlConnection(myConnectionString);

try
{
    myConnection.Open();
    SqlBulkCopy myCommand = new SqlBulkCopy(myConnection);

    myCommand.DestinationTableName = "myDestinationTableName";

    //Below method has four overloads; 
    //of which I am interested in the two mentioned below.
    myCommand.WriteToServer();

    myCommand.Close();
}
finally
{
    myConnection.Close();
}

But I stumbled upon these two versions of WriteToServer method.

  1. SqlBulkCopy.WriteToServer Method (IDataReader)

  2. SqlBulkCopy.WriteToServer Method (DataTable)

Question : What are the pros and cons of one over another? Which one is faster?


Solution

  • With the default case, both should have similar performance otherwise horses..

    But there is one difference though, WriteToServer with DataTable as parameter will insert all rows from DataTable , but with IDataReader copy starts with next available row in the reader (which would be set to first row in default case).

    Remember, IDataReader provides a read-only/forward only mechanism, so there is a concept of current position/row index, whereas with DataTable there is no such thing. With each Read on IDataReader row index moves to next row.