简体   繁体   中英

SqlBulkCopy string NULL CSV

I'm trying to mass-insert a CSV file into a SQL Server database.

The process is .CSV files DataTable for SqlBulkCopy SQL Server.

In the file I have several NULL that this code returns as text, and should not be text:

 var linea = line.Split(delimiter);
 row = dt.NewRow();

 for (j = 0; j < linea.Length; j++)
 {
     if (linea[j].ToString().ToLower() == "null")
     {
          row[j] = DBNull.Value; 
     }
}

dt.Rows.Add(row);

It's pretty vague on what's your problem is, but I think I know you want the data to be stored as datatype NULL instead of a string "NULL" in the DB.

From what I know about SQLBulkCopy into datatable, you can't manipulate the data to store NULL in database table. To deal with this, I used two work-around:

  1. Remove the "NULL" inside the CSV before uploading. If the CSV comes from your users, advise them not to use "NULL" for cell that is suppose to be blank/empty. Just leave the cell blank. This is the most direct way, because the datatable will somehow store NULL into database table when the cell is blank.

  2. Pretty sluggish way, replace all "NULL" value in datatable to blank ("") and store into database table. When SQLBulkCopy inserted all data, run an update statement to update all blank column to NULL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM