IDataReader vs DataTable; pros and cons

c# datatable idatareader sqlbulkcopy


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

So I am using SqlBulkCopy.

SqlConnection myConnection = new SqlConnection(myConnectionString);

    SqlBulkCopy myCommand = new SqlBulkCopy(myConnection);

    myCommand.DestinationTableName = "myDestinationTableName";

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


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?

5/25/2015 2:56:40 PM

Accepted Answer

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.

5/25/2015 3:02:32 PM

Popular Answer

Overload with DataTable is intended for the cases, when you already have suitable DT somewhere in your application.

Overload with IDataReader, in turn, is for the cases, when there is some query (either raw query text, or constructed command, it doesn't matter). In this case, creation of intermediate data container, such as DT, is unnecessary. Hence, this overload allows you to fetch data directly from reader.

Assuming, that you haven't neither DT, nor IDataReader, the second one should at least consume less resources.

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow