Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
1  
Does your column accept null values at all? –  MarcinJuraszek 19 hours ago
 
Are you aware that sFromPeriod and sTempFromPeriod is not the same thing? –  zespri 19 hours ago
 
Look into nullable data type ( SqlDateTime?) –  Sadek 18 hours ago

1 Answer

Consider using DBNull.Value instead of SqlDateTime.Null.

For example:

cmd.Parameters["@FromPeriod"].Value = DBNull.Value;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.