Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert null in datetime type column in sql server

Tags:

c#

sql-server

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;
}
like image 727
Abhishek Pandey Avatar asked Aug 07 '13 08:08

Abhishek Pandey


1 Answers

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).

like image 106
Dr Schizo Avatar answered Sep 22 '22 06:09

Dr Schizo