3

I have a nullable DateTime Variable. And I want to write it to SQL DB. When i try to insert:

If the variable has value there is no problem.

But if it hasn't a value, insertion interrupting with an error.

I want to ask: How can we insert nullable DateTime to Sql via DbCommand Parameter?

(P.S. : Sql column is nullable too.)

DateTime? myDate = null;
DbCommand dbCommand = new DbCommand();
dbCommand.Parameters.Add("NullableSqlDateField", DbType.DateTime, myDate);
3
  • What's the error you get? I believe you can use null and DBNull.Value interchangeably. Commented Dec 29, 2011 at 14:48
  • 1
    @Yuck - I don't think you can use the two interchangeably, or at the very least, you can't with all database providers. You should use DBNull.Value when inserting null values into a database. There is a slight difference in semantics when dealing with null vs. DBNull.Value: null refers to an invalid object reference, whereas DBNull.Value refers to an unknown value in a database row. Seems like hair-splitting, but it's the best reasoning I can see for the difference. Commented Dec 29, 2011 at 17:20
  • @mjd79 It works with SqlDbCommand, maybe just not with DbCommand. Commented Dec 29, 2011 at 17:51

2 Answers 2

13

Try the null coalescing operator:

dbCommand.Parameters.Add("NullableSqlDateField", DbType.DateTime, (object) myDate ?? DbNull.Value);
Sign up to request clarification or add additional context in comments.

1 Comment

I'm a bit surprised that this is not handled by the db provider.
0

try this

if(myDate.HasValue)
  dbCommand.Parameters.Add("NullableSqlDateField", DbType.DateTime, myDate.Value);
else
  dbCommand.Parameters.Add("NullableSqlDateField", DbType.DateTime, DbNull.Value);

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.