日期时间问题与01/01/1900

我在sql server中有一个datetime列及其可选字段,如果用户决定不输入,那么我想在表中插入值为NULL,我定义如下:

@deadlineDate datetime = null 

当我插入到SQL服务器时,我在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; } 

但问题是:它的插入

 1900-01-01 00:00:00.000 

在sql表中而不是NULL

我在这做错了什么?

更新:

 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; } 

假设你有:

 DateTime? date = GetDate(); command.Parameters.Add("@date").Value = date; 

如果date == null你要插入SQL NULL,即DBNull.Value那么你应该做下一步:

 DateTime? date = GetDate(); command.Parameters.Add("@date").Value = (object)date ?? DBNull.Value; 

这意味着:

 if(date != null) // use date else // use DBNull.Value 

如果你想在你的函数中关注可为空的日期时间,你应该在下一步声明它:

 private object GetDate() { DateTime date; return DateTime.TryParse(selectedDate, out date) ? date : DBNull.Value; } command.Parameters.Add("@date").Value = GetDate(); 

但我不建议这样做并使用下一个:

 command.Parameters.Add("@date").Value = (object)GetDate() ?? DBNull.Value; 

插入SQL Server时需要DBNull.Value而不是null

在.NET中设置DateTime = null ,它采用DateTime的最小值01-01-0001。

我假设您在SQL Server中使用SMALLDATETIME ,其最小值为’01 / 01/1900′

如果您将查询作为参数(字符串类型)发送到另一个执行查询的方法,如下所示:

  int userno = 123; string date_variable = null; string query = string.Format( @"INSERT INTO system_log (userno,ref_date) values ({0},'{1}');",userno,date_variable); obj.executeInsert(query,conn); 

这可能会在使用ExecuteNonQuery()或其他内容执行时再次保存默认日期。

甚至传递(对象)date_variable ?? DBNull.Value; 不会在这种情况下工作

然后你可以简单地将date_variable设置为“null”

  if (string.IsNullOrEmpty(date_variable)) date_variable= "null"; else date_variable= "'" + date_variable+ "'"; string query = string.Format( @"INSERT INTO system_log (userno,ref_date) values ({0},{1});",123,date_variable); obj.executeInsert(query,conn);