Return NULL datetime value from T-SQL into C# Data

2019-07-11 04:28发布

问题:

This value (row[10]) is coming from a DataRow object, from a SQL result set in T-SQL. I believe it has a type "object". In my database, I have a value of NULL for this field for this particular record, but it's returning an empty string in my result set, not a null value. I'd like to fix the root problem and have my result set return NULL instead of an empty string, but if that's not possible, making this code more efficient would be just fine--meaning the 1st snippet, since it works for all 3 cases.

This works when row[10].ToString() is equal to an empty string, null or a DateTime format, but I'd like to shorten it. This is my workaround for now.

        string temp0 = row[10].ToString();
        DateTime? temp = null;
        if (temp0 == "")
        {
            temp0 = null;
        }
        if (temp0 != null)
        {
            temp = DateTime.Parse(temp0);
        }

        d.date_migrate_prod = temp == null ? null : temp;

This works for a null datetime value, an actual datetime value, but not when row[10] is equal to an empty string.

        DateTime? temp = DateTime.Parse(row[10].ToString());
        d.date_migrate_prod = temp == null ? null : temp;

回答1:

The following should work as a shortcut:

DateTime? temp = String.IsNullOrEmpty(row[10].ToString())? null : DateTime.Parse(temp0);


回答2:

The correct way to do this is:

 DateTime? temp = null; //this is fine
 var indexOfYourColumn = reader.GetOrdinal("columnName");//not necessary but makes iterating faster
 while (reader.Read())
 {
       temp = reader[indexOfYourColumn] != DBNull.Value ? (DateTime?) null : DateTime.Parse(reader[indexOfYourColumn].ToString())
 }

Why? You can't do .ToString() on a null. You then need to cast like to like. So nullable DateTime to nullable DateTime.

This was asked long time ago. But the accepted answer is not correct.



回答3:

An answer to the stated question.

string temp0 = row[10].ToString();
DateTime?;
if (string.IsNullOrEmpty(temp0)) 
{
    temp = null;
}
else
{
    temp = DateTime.Parse(temp0);
}

Could use DateTimeTryParse.
Can pass a null but it will parse to 1/1/0001



回答4:

Try:

DateTime? localvariable 
      = row[10] == Convert.DBNull ? null : Convert.ToDateTime(row[10].ToString())