Reputation: 21
I have the following code:
SqlDateTime sqldatenull = SqlDateTime.Null;
sSql = "INSERT INTO mydb.dbo.myTable(FromPeriod) Values (@FromPeriod)";
if (sFromPeriod.Length == 0) {
cmd.Parameters.Add("@FromPeriod", SqlDbType.DateTime);
cmd.Parameters["@FromPeriod"].Value = sqldatenull;
} else {
cmd.Parameters.AddWithValue("@FromPeriod", sTempFromPeriod);
}
cmd.ExecuteNonQuery();
sFromPeriod is a date and when it's length is zero, I receive error: Conversion failed when converting date and/or time from character string. When sFromPeriod has a value, the code works fine. I have also used DBNull.Value in place of sqldatenull and received the same error. What am I missing?
Upvotes: 0
Views: 3076
Reputation: 21
Consider using DBNull.Value
instead of SqlDateTime.Null
.
For example:
cmd.Parameters["@FromPeriod"].Value = DBNull.Value;
Upvotes: 2