How does one convert a C# Datetime into the equivalent SQL DATE type, so that I can do a simple equality in a WHERE clase, with no parametisation?
-
8Why don't you want to use parameters for that?Manuel Rauber– Manuel Rauber2012-04-19 12:07:14 +00:00Commented Apr 19, 2012 at 12:07
-
3SQL parameters are safer and provide strong typing which can prevent a lot of typing errors in SQL queries. There's really not a good reason not to use them.David Anderson– David Anderson2012-04-19 12:09:14 +00:00Commented Apr 19, 2012 at 12:09
-
@Raubi, internal batch job and I have been told not to bother....intrigued_66– intrigued_662012-04-19 12:11:25 +00:00Commented Apr 19, 2012 at 12:11
-
2By the time you have written this question, waited for the answer and understood it you could have used a parameter many times over.Richard– Richard2012-04-19 12:24:18 +00:00Commented Apr 19, 2012 at 12:24
4 Answers
Simply convert it to a iso string.
Date and Time
YourDateTime.ToString("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");
Only Date
YourDateTime.ToString("yyyy-MM-dd");
But i really encourage you to use parameterized queries because you will generate a new Sql Execution plan everytime your T-SQL query is different.
If you use Parameters you will get only one plan. This results in better performance.
More Information
Comments
If you are talking about SqlDateTime structure you can use its constructor which accepts a value of DateTime type:
See MSDN: SqlDateTime Constructor (DateTime)
Comments
I think other answers didn't really understand your question (or I didn't)
From what I gathered you're asking how to convert from C# DateTime to SQLs Date type (not sql datetime!). All other answers included time in their answer.
If that's true, you don't have to worry about it at all. SQL Date is fully compatible with .NETs DateTime so just passing it to procedure will strip the time part and pass the date correctly.