datetime issue with 01/01/1900

后端 未结 3 1734
慢半拍i
慢半拍i 2020-12-16 21:17

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 somethin

相关标签:
3条回答
  • 2020-12-16 21:55

    Assuming you have:

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

    in case when date == null you want to insert SQL NULL i.e. DBNull.Value so you should do next:

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

    which means the same as:

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

    if you want to take care about nullable datetime in your function you should declare it next way:

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

    but I don't recommend to do that and use next:

    command.Parameters.Add("@date").Value = (object)GetDate() ?? DBNull.Value;
    
    0 讨论(0)
  • 2020-12-16 21:59

    If you are sending query as parameter (of string type) to another method which executes the query like the one below:

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

    This might again save the default date when executed using ExecuteNonQuery() or something else.

    Even passing (object)date_variable ?? DBNull.Value; wont work in this scenario

    Then you can simply set date_variable as "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);
    
    0 讨论(0)
  • 2020-12-16 22:11

    You need DBNull.Value rather than null when inserting into SQL server.

    When you set DateTime = null in .NET it takes the minimum value of DateTime which is 01-01-0001.

    I'd assume you are using a SMALLDATETIME in SQL Server where the minimum value is '01/01/1900'

    0 讨论(0)
提交回复
热议问题