How to use BulkCopy without Defining the Destination Table

c# datatable sql sqlbulkcopy

Question

All,

I have the following BulkCopy operation:

// Convert the FlexGrid to a DataTable.
DataTable currData = (DataTable)c1ErrFlexGrid.DataSource;

// Insert the data into the database.
SqlBulkCopy SqlBulkIns = new SqlBulkCopy(strConnString, SqlBulkCopyOptions.Default);
SqlBulkIns.BatchSize = 5000;
SqlBulkIns.DestinationTableName = String.Format("dbo.{0}", strTableName);
SqlBulkIns.WriteToServer(currData);

where strConnectionString is a defined and valid connection string. This has worked fine in the past when the table strTableName exists and the fields are defined. I now wish to perform this BulkCopy operation on a DataTable that is defined at run-time; that is, without predefining the table structure in SQL. Is this possible? If so, how?

Thanks for your time.

Accepted Answer

You could use this SqlTableCreator object to create a SQL table from your datatable and then run the bulk insert.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why