Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping columns in a DataTable to a SQL table with SqlBulkCopy

I would like to know how I can map columns in a database table to the datatable in c# before adding the data to the database.

using (SqlBulkCopy s = new SqlBulkCopy(conn)) {     s.DestinationTableName = destination;     s.WriteToServer(Ads_api_ReportData); } 
like image 465
user2545743 Avatar asked Jul 04 '13 11:07

user2545743


People also ask

What is SqlBulkCopy in SQL?

The SqlBulkCopy class lets you write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example), but SqlBulkCopy offers a significant performance advantage over them.

What is the use of SqlBulkCopy command?

Bulk means many things. So with the use of SqlBulkCopy you can send a large amount of data from any source to SQL Server database. For example you have a collection of data in XML format and you want to save this data into your database table. You can do this very easily.

How does SqlBulkCopy update data?

Upload the data to the temporary table, then perform the SqlBulkCopy update. Using SqlBulkCopy(), upload the datatable's data to the temporary table. Then execute a SQL command to update the main table's data from the temporary table. Finally drop the temporary table.


1 Answers

You probably need some thing like

 public void BatchBulkCopy(DataTable dataTable, string DestinationTbl, int batchSize) {     // Get the DataTable      DataTable dtInsertRows = dataTable;      using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity))     {         sbc.DestinationTableName = DestinationTbl;          // Number of records to be processed in one go         sbc.BatchSize = batchSize;          // Add your column mappings here         sbc.ColumnMappings.Add("field1","field3");         sbc.ColumnMappings.Add("foo","bar");          // Finally write to server         sbc.WriteToServer(dtInsertRows);     }     } 

Ref: How to use SqlBulkCopyColumnMappingCollection? . .

Seel also http://www.codeproject.com/Articles/18418/Transferring-Data-Using-SqlBulkCopy

like image 190
StackTrace Avatar answered Sep 19 '22 03:09

StackTrace