Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .net Datetime in sql query

I have a DateTime object I want to compare against an sql datetime field in a where clause. I'm currently using:

"where (convert( dateTime, '" & datetimeVariable.ToString & "',103) <= DatetimeField)"

But I believe datetimeVariable.ToString will return a different value depending on the culture where the system is running.

How would you handle this so it is culture independent?

EDIT : I won't be using paramatised sql in this code...

EDIT : following Parmesan's comment to one of the answers looks like the best method may be:

"where (convert( dateTime, '" & datetimeVariable.ToString( "s" ) & "',126) <= DatetimeField)"
like image 652
Patrick Avatar asked Dec 13 '22 22:12

Patrick


1 Answers

Don't use string concatenation, use a parameterised query. Pass in a parameter value of type DateTime. This avoids the formatting issue altogether, improves performance for subsequent queries, and gets around the inherent vulnerabilities (SQL injection) that you lay yourself open to when forming SQL in this way.

"where @dateTime <= DateTimeField"

Then set the parameter @dateTime. If you need more, tell us a bit more about your code - straight ADO.NET, Enterprise Library, something else?

like image 57
David M Avatar answered Dec 15 '22 14:12

David M