Home > other >  How to convert a value if it's null
How to convert a value if it's null

Time:07-22

I am using C#

Convert.ToDateTime(rdr["Termination_Date"])

rdr is defined as

OracleDataReader rdr = cmd.ExecuteReader();

The Termination_Date field in the table maybe null. How do I check if it's null and set a date like 01/01/0001

CodePudding user response:

If you have to access the column by name, you can compare against DBNull.Value with something like a ternary statement to pick between DateTime.MinValue (1/1/0001) and the result of converting the non-null value.

OracleDataReader rdr = cmd.ExecuteReader();

DateTime terminationDate = rdr["Termination_Date"] == DBNull.Value
    ? DateTime.MinValue
    : Convert.ToDateTime(rdr["Termination_Date"]);

You can do this more concisely with OracleDataReader.IsDBNull() and OracleDataReader.GetDateTime() if you know the column index (assume that our desired value is the first column in the result).

OracleDataReader rdr = cmd.ExecuteReader();

DateTime terminationDate = rdr.IsDBNull(0)
    ? DateTime.MinValue
    : rdr.GetDateTime(0);

CodePudding user response:

Try this:

DateTime result = DateTime.MinValue;
int index = rdr.GetOrdinal("Termination_Date");
if(!rdr.IsDbNull(index))
   result = rdr.GetDateTime(index);

Reference: OracleDataReader.GetDateTime(Int32) Method

An explanation: with DataReader classes, database nulls come across as the value DBNull.Value. You need to check for that value (there are various methods) before attempting to convert to the desired data type.

DateTime.MinValue is equivalent to 1/1/0001.

If you'd like to segue into using nullable variables rather than a "special value" to symbolize "no value", you could try this extention method (done from memory):

public static class Extensions {

    public static T? GetNullableValue<T>(
       this System.Data.Common.DbDataReader reader, 
       string columnName) where T : struct {
   
         var ordIndex = reader.GetOrdinal(columnName);
         if(reader.IsDbNull(ordIndex))
             return null;
         else
             return (T?) reader.GetValue(ordIndex)
     }
}
  • Related