I have decided to replace/convert DataTable to IDataReader due to memory issues.
After quite a while of Google & MSDN searches, I came across this at http://www.michaelbowersox.com/2011/12/22/using-a-custom-idatareader-to-stream-data-into-a-database/ and Bulk Insert Sql Server millions of record .
Since I'm using LumenWorks Fast CSV Reader and I haven't yet figure out how tell the CsvReader to have IDataReader to use 2 different field versions. :-( The csvReader.FieldCount is the key here but I don't see how to tell CsvReader to use either of the 2 new classes having IDataReader interface. See the original script and modified script below... Thanks...
//Original scripts...
var dbConnection = new SqlConnection(_dbConnectionString);
using (var dbBulkCopy = new SqlBulkCopy(dbConnection)
{
using (CsvReader csvReader = new CsvReader(new StreamReader(filePath), false, '|', '"', '\\', '#', ValueTrimmingOptions.UnquoteOnly))
{
while(csvReader.ReadNextRecord())
{
if (csvReader.FieldCount == 48)
{
//Version 1...
dataRow["DealerId"] = csvReader[0];
dataRow["DealerName"] = csvReader[1];
//Etc...
}
else if (csvReader.FieldCount == 51)
{
//Version 2...
dataRow["DealerId"] = csvReader[0];
dataRow["DealerName"] = csvReader[1];
//Etc...
}
else { throw new Exception("Field Total Count Mismatched"); }
dataTable.Rows.Add(dataRow);
}
dbConnection.Open();
dbBulkCopy.WriteToServer(dataTable);
}
}
//New script...
var dbConnection = new SqlConnection(_dbConnectionString);
using (var dbBulkCopy = new SqlBulkCopy(dbConnection)
{
dbConnection.Open();
using (CsvReader csvReader = new CsvReader(new StreamReader(filePath), false, '|', '"', '\\', '#', ValueTrimmingOptions.UnquoteOnly))
{
csvReader.ReadNextRecord();
dbBulkCopy.WriteToServer(
if (csvReader.FieldCount == 48)
{
//Version 1...
csvReader....??? //Assign a custom class having IDataTable...
}
else if (csvReader.FieldCount == 51)
{
//Version 2...
csvReader....??? //Assign a custom class having IDataTable...
}
else { throw new Exception("Field Total Count Mismatched"); }
);
}
}
//Sample Script...
using (var file = new StreamReader(path))
using (var csv = new CsvReader(file, true)) // true = has header row
using (var bcp = new SqlBulkCopy(connection)) {
bcp.DestinationTableName = "TableName";
bcp.WriteToServer(csv);
}