0

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?

3
  • 1
    Does your column accept null values at all? Commented Nov 17, 2013 at 21:08
  • Are you aware that sFromPeriod and sTempFromPeriod is not the same thing? Commented Nov 17, 2013 at 21:43
  • Look into nullable data type ( SqlDateTime?) Commented Nov 17, 2013 at 22:31

1 Answer 1

2

Consider using DBNull.Value instead of SqlDateTime.Null.

For example:

cmd.Parameters["@FromPeriod"].Value = DBNull.Value;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.