Nic*_*ahn 8 c# sql t-sql sql-server datetime
我在sql server及其可选字段中有一个datetime列,如果用户决定不输入,那么我想在表中插入值为NULL,我定义如下:
@deadlineDate datetime = null
Run Code Online (Sandbox Code Playgroud)
当我插入到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;
}
Run Code Online (Sandbox Code Playgroud)
但问题是:插入
1900-01-01 00:00:00.000
Run Code Online (Sandbox Code Playgroud)
在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;
}
Run Code Online (Sandbox Code Playgroud)
您需要DBNull.Value而不是null插入SQL服务器时.
DateTime = null在.NET中设置时,其最小值DateTime为01-01-0001.
我假设您SMALLDATETIME在SQL Server中使用最小值为'01/01/1900'的SQL Server
假设你有:
DateTime? date = GetDate();
command.Parameters.Add("@date").Value = date;
Run Code Online (Sandbox Code Playgroud)
如果date == null你想插入SQL NULL,DBNull.Value所以你应该做下一步:
DateTime? date = GetDate();
command.Parameters.Add("@date").Value = (object)date ?? DBNull.Value;
Run Code Online (Sandbox Code Playgroud)
这意味着:
if(date != null)
// use date
else
// use DBNull.Value
Run Code Online (Sandbox Code Playgroud)
如果你想在你的函数中关注可为空的日期时间,你应该在下一步声明:
private object GetDate()
{
DateTime date;
return DateTime.TryParse(selectedDate, out date) ? date : DBNull.Value;
}
command.Parameters.Add("@date").Value = GetDate();
Run Code Online (Sandbox Code Playgroud)
但我不建议这样做并使用下一个:
command.Parameters.Add("@date").Value = (object)GetDate() ?? DBNull.Value;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31510 次 |
| 最近记录: |