Ein passabler Weg über ADO.NET eine große Menge von Inserts nacheinander zu machen ist SqlBulkCopy() - damit spart man sich aufwändiges Schleifenlaufen oder Programmieren von Stored Procedures.

Beispiel:

DataTable source = new DataTable("Industries");

DataColumn col = new DataColumn();
col.DataType = System.Type.GetType("System.Int32");
col.ColumnName = "FkAddressItemId";
source.Columns.Add(col);

col = new DataColumn();
col.DataType = System.Type.GetType("System.Int32");
col.ColumnName = "FkAddressMachineTypeId";
source.Columns.Add(col);

DataRow item;

foreach (AddressIndustry industry in a.Industries)
{
item = source.NewRow();
item[0] = newAddressID;
item[1] = industry.ID;
source.Rows.Add(item);
}

using (SqlBulkCopy bulk = new SqlBulkCopy(connection))
{
bulk.DestinationTableName = "ComboMachineTypesItems";
bulk.ColumnMappings.Add("FkAddressItemId", "FkAddressItemId");
bulk.ColumnMappings.Add("FkAddressMachineTypeId",
"FkAddressMachineTypeId");
bulk.WriteToServer(source);
}

Der Vorteil: Speed, Speed, Speed!

Kommentare

#1 software development london schrieb am Dienstag, 11. August 2009 11:00:00:
Cool,
Thanks for writing, most people don't bother.
So far all the examples I have seen for bulkcopy where with DataTable ,where else can we use sqlbulkcopy?

Dein Kommentar