07 June 2011

Handle Null Dates from C# to SQL

Although this has been dealt with hundreds of times, this post is more of a "note to self" so I don't have to go hunting every time I need to handle optional dates from a data access layer into sql. Figured you might find it useful too.
// public getter/setters
public DateTime? OptDate { set; get; }

// for inserts
string sql = "INSERT INTO MyTable (..., OptDate) VALUES (..., @OptDate)";
SqlParameter[] parameters = new SqlParameter[] { 
  new SqlParameter("@OptDate", (object)DBNull.Value)
};

// and for updates
string sql = "UPDATE MyTable SET (..., OptDate = @OptDate)";
SqlParameter[] parameters = new SqlParameter[] { 
  new SqlParameter("@OptDate", 
    (OptDate.HasValue ? OptDate : (object)DBNull.Value))
};

Works well on Guid's too.