簡體   English   中英

datetime issue with 01/01/1900

[英]datetime issue with 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;          
}

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

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

我假設您在SQL Server中使用SMALLDATETIME ,其最小值為'01 / 01/1900'

假設你有:

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;

如果您將查詢作為參數(字符串類型)發送到執行查詢的另一個方法,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM