How to insert null in datetime type column in sql server

c#, sql-server

Solution

cmd1.Parameters["@InsertDate"].Value = getDate ?? DBNull.Value;

The key being DBNull.Value. I imagine you have a nullable DateTime variable, i.e. `DateTime? someVariable`. You can test it for null and if it is use `DBNull.Value` (as shown above).

Problem

I have a table in which there are some datetime type columns. I use a stored procedure to insert values into the table. In the stored procedure I have variables that accept null for inserting into the table. My problem is when I try to insert a null value into my table's datetime column it throws error. my code is as. ``` System.Data.SqlTypes.SqlDateTime getDate; //set DateTime null getDate = SqlDateTime.Null; if (InsertDate.Text == "") { cmd1.Parameters["@InsertDate"].Value = getDate; } else { cmd1.Parameters["@InsertDate"].Value = InsertDate.Text; } ```

Original source