Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set constant value to some columns in SqlBulkCopy

I'm trying transfer data from "csv" file to SQL Database. Is it possible to map some fields by default vale which not exsits in "csv" file? Something like shown below: bulkCopy.ColumnMappings.Add("Destenition_column_name", "constant_value");

Thanks for advance!

like image 611
user3818229 Avatar asked Dec 08 '25 08:12

user3818229


2 Answers

What about setting a default column BEFORE populating the DataTable?

var returnTable = new DataTable();
returnTable.Columns.Add("Constant_Column_Name").DefaultValue = "Constant_Value";

If you then add rows each row will always have the specified default value for this column without explicitly setting it.

like image 140
Anytoe Avatar answered Dec 09 '25 23:12

Anytoe


Anytoe's answer can be useful if you create DataTable by yourself. But there could be a situation when you are getting the dataTable from some library method so you trick with default value will not work. For this case I found this solution:

var dt = await  GetDataTable();
dt.Columns.Add("ImportFileId", typeof(long), importFileId.ToString());

This is a feature named "Expression Columns". For example, you can use this solution with the ExcelDataReader library which has ".dataset()" method.

And you always can just loop through the rows if you don't want to use "Expression Columns" :

 foreach (DataRow dr in dt.Rows)
 {
   dr["ImportFileId"] = importFileId.ToString();
 }

Info: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/creating-expression-columns

like image 45
Stanislav Avatar answered Dec 09 '25 23:12

Stanislav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!