0

How should I be using c# datetime values in my C# queries?

Up until now I've been doing the following:

Datetime my_time = new DateTime(2012, 09, 05);
cmd.Parameters.AddWithValue("@date", my_time);
cmd.CommandText = "SELECT * FROM sales WHERE date = @date";

Which has been working fine until this morning when I've been getting null errors when retrieving values from the results set.

I changed my date parameter to grab the short date string from my datetime value like this:

cmd.Parameters.AddWithValue("@date", my_time.ToShortDateString());

And it appears to be working fine again.

What is the correct way of doing this? Obviously I'm converting my datetime value to a string, only (presumably) for the database to convert it back to a datetime before evaluating my equality where clause, which seems a little pointless.

Edit:

I'm using SQL Server Compact Edition and the date field in my example has a precision setting of 8 (date, excluding time right?). Does that mean I was passing the full date with 00:00:00.000 on the end before? How might I pass a datetime value to the database without including the time, without converting to a string first?

1
  • Exactly what error are you getting? Commented Sep 7, 2012 at 10:09

3 Answers 3

2

You can just try with my_time.Date

cmd.Parameters.AddWithValue("@date", my_time.Date);
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I needed - I was most the way there on my own, but thanks. :)
0

Do not pass it as a string or will run in troubles with culture formatting.

Try using SqlDateTime instead.

Comments

0

You're not converting the date to a string - AddWithValue knows it is a date, but it is a datetime, so it has a time component. Do your sales have a time component to them?

 SELECT * FROM sales WHERE DateDiff(d, @date, date) = 0

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.