2

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?

Devraj Gadhavi
  • 3,541
  • 3
  • 38
  • 67

2 Answers2

2

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.

Habib
  • 219,104
  • 29
  • 407
  • 436
1

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.

Dennis
  • 37,026
  • 10
  • 82
  • 150