i have a datetime column in sql server and its optional field and if the user decided not to enter then i want to insert the value as NULL in the table and i define something like this:
@deadlineDate datetime = null
when i am inserting into sql server i have this code in asp.net
private DateTime? GetDeadlineDate()
{
DateTime? getDeadlineDate = null;
if (!string.IsNullOrEmpty(DeadlineDate.SelectedDate))
{
getDeadlineDate = DateTime.Parse(DeadlineDate.SelectedDate).Date;
}
if (!getDeadlineDate.HasValue)
{
return null;
}
return getDeadlineDate.Value;
}
but the problem is: its inserting
1900-01-01 00:00:00.000
in the sql table instead of NULL
what i am doing wrong here?
UPDATE:
private DateTime? GetDeadlineDate()
{
DateTime? getDeadlineDate = null;
if (!string.IsNullOrEmpty(DeadlineDate.SelectedDate))
{
getDeadlineDate = DateTime.Parse(DeadlineDate.SelectedDate).Date;
}
if (!getDeadlineDate.HasValue)
{
return DBNull.Value; //throws error....
}
return getDeadlineDate.Value;
}
Assuming you have:
in case when
date == nullyou want to insert SQL NULL i.e.DBNull.Valueso you should do next:which means the same as:
if you want to take care about nullable datetime in your function you should declare it next way:
but I don’t recommend to do that and use next: