Compare DateTime null value in SQL and in C#

I am trying to use compare dates in a query. I have d and p are rows selected from different datatables.I want to retrieve fields from datatables based on condition. I have below conditions but throwing an error when any one of the below date is Null or empty.

I tried below statements-

  • Generate a XML and update it in a table in sql server without using cursor
  • Sql Server Case Statement gives me errors in user-defined function
  • System.Threading.ThreadAbortException: Thread was being aborted
  • Delete all rows in table
  • Backup SQL Server database from windows form application by a button click
  • Setting multiple variables from a Execute SQL Task result object with a single row
  • join d in Data.AsEnumerable()
                        on p.Field<String>("EMPLID") equals
                        d.Field<String>("EMPLID")
     where (Convert.ToString(d.Field<DateTime>("CONTRACT_START"))!=null) &&  (Convert.ToString(d.Field<DateTime>("SIGNED_DT"))!=null) && (Convert.ToString(d.Field<String>("ACT_DT"))!=null)
    

    Throwing an error- Can not cast DBNull.Value to Sysytem .date Time . Please use a nullable types.

    when above condition is true( values are not null then I want to exceute below statement in a query)

     where (d.Field<DateTime>("CONTRACT_START") >= sd && d.Field<DateTime>("CONTRACT_START") <= ed) ||Convert.ToString(d.Field<DateTime>("SIGNED_DT"))!=" " && d.Field<DateTime>("SIGNED_DT") > d.Field<DateTime>("CONTRACT_START") || d.Field<DateTime>("ACT_DT") > d.Field<DateTime>("CONTRACT_START"))
    

    How to check if the values are not null then execute the condition using in a query in C#.

  • Using Sql Spatial Data (C#) to find the “visual” center of irregular polygons
  • EXEC sp_spaceused query
  • SqlBulkCopy and DataTables with Parent/Child Relation on Identity Column
  • How to monitor database updates from application?
  • Write utf-8 to a sql server Text field using ADO.Net and maintain the UTF-8 bytes
  • Entity Framework 6 - Timing queries
  • 2 Solutions collect form web for “Compare DateTime null value in SQL and in C#”

    Yes, that’s cause your value is null in your datatable. You should change the line in your where condition to be (notice the nullable DateTime DateTime?)

    (Convert.ToString(d.Field<DateTime?>("CONTRACT_START"))!=null)
    

    I’m not proficient in MySql, but you are definately using DateTime the wrong way. In c# DateTime is struct, which means it cannot be null.

    You have to use Nullable dates in your c# project instead (MSDN: Using Nullable Types):

    DateTime? dateTime;
    
    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.