Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting DBNull value to a DataTable column before bulk copy

I have a data table that I use for Bulk Copying into a SQL server Database: I define its columns as follows:

dt.Columns.Add("BaseID", typeof(Int32));
dt.Columns.Add("ContractID", typeof(DateTime));
dt.Columns.Add("TermID",typeof(Int32));
dt.Columns.Add("Price",typeof(Decimal));
dt.Columns.Add("PeakType",typeof(String));

Now the PeakType column could actually be a string or it could be null. So when I add rows to my data table I do this.

DataRow row = dt.NewRow();
row["BaseID"] = baseID;
row["ContractDate"] = contractDate;
row["TermID"] = termID;
row["Price"] = price;
row["PeakType"] = peakType; //How would I assign If I want to assign DBNull?

How do I specify DBNull.Value if peakType is null so that my bulk copy would correctly insert a null in the column in the SQL server table

like image 327
Sai Avatar asked Mar 19 '14 20:03

Sai


People also ask

Does not allow DBNull value SQL?

The two possible reasons I know of for the does not allow DBNull error are: Columns are in the wrong order, which is solved by either putting them in the same order as their Database Ordinal, or by performing a Column Mapping. KeepNulls is enabled, and DBNull. Value (or null ?) are set in the DataTable.

What does DBNull value return?

DBNull represents a nonexistent value returned from the database. In a database, for example, a column in a row of a table might not contain any data whatsoever. That is, the column is considered to not exist at all instead of merely not having a value. A DBNull object represents the nonexistent column.

What is DBNull value in SQL Server?

DBNull is a singleton class, which means only this instance of this class can exist. If a database field has missing data, you can use the DBNull. Value property to explicitly assign a DBNull object value to the field. However, most data providers do this automatically.


1 Answers

Use the null coalescing operator.

row["PeakType"] = peakType ?? DBNull.Value;

If peakType is null, it will use the correct DB null value.

like image 66
TyCobb Avatar answered Sep 23 '22 18:09

TyCobb