Type mismatch in C# SqlBulkCopy

c# sqlbulkcopy


I have a DataTable which has 10 columns, and after I add some rows in it, I want to add it to the database using SqlBulkCopy.

My problem is that in the DataTable I have strings and some fields in the database are decimal and date respectively. Is there a way to convert them to the desired data types?

2/15/2012 12:18:19 PM

Accepted Answer

When programmatically adding columns to your DataTable, you can specify type:-

DataTable dt = new DataTable();
dt.Columns.Add("FieldName", typeof(System.Decimal));

These will be honored when you perform the bulk copy.


In response to user comment.

When populating the DataRow with information, an explicit conversion is only required if the source data doesn't match the target field.

If the types are the same, you can just assign it.


// With a decimal field, decimal target
Decimal myNum = 123;
// Works fine - assuming the Price datacolumn has been set up as a System.Decimal
row["Price"] = myNum;
2/15/2012 2:10:17 PM

Popular Answer

Sounds like you may be creating the columns in the DataTable in code (as opposed to Filling via a DataAdapter which would set the column data types appropriately).

If that's the case, then can you not just create the DataColumns with the correct data types to start with, instead of all strings...and then ensure when you add rows to it, you convert the data into the appropriate type?

i.e. get to the point where your DataTable has the correct types and data in correctly, so SqlBulkCopy can then blast it into the DB with data already in the correct form.

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow