views:

294

answers:

2

I am passing an ad-hoc Insert statement from c# application to the sql server 2000/2005. Sometimes, if machine (where sql server is installed) datetime format is different than what I am passing in, it is throwing an error.

e.g. : In Insert statement I am passing '2010-03-10 00:00:00-05:00' this but machine regional date setting is different. I am getting this error:-

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.

Can I pass some generic date format in Insert statement from c# that works perfectly with any machine Regional Date Time settings.?

+4  A: 

"yyyymmdd" is safest, the basic ISO-8601 format. "yyyy-mm-dd" has issues as the link below mentions

With times: "yyyymmdd hh:mm:ss"

SQL Server can be slightly odd when dealing with datetimes. It's mostly fixed in SQL Server 2008 with the new date and time formats. The definitive article by Tibor Karaszi

Edit: And another article by Tony Rogerson for the unbelievers

gbn
date/times, just got to love them, now toss in JSON and ajax for some more fun :) +1 for the links
Mark Schultheiss
+1  A: 
Simon P Stevens
Unfortunately, SQL won't handle this format
gbn
@gbn. Which bit, the parameters/stored procs or the ISO 8601 string?
Simon P Stevens
Your ISO 8601 string. See my answer please about why the yyyy-mm-dd is SQL language setting dependent. Using stored procs/params is better because .net would handle the translation and SQL Server would get a native datetime value
gbn
@gbn. Really!? Crazy. I'll have to check that out.
Simon P Stevens
Or you could read the 2 links in my answer
gbn
@gbn, yeah thanks. I have. always good to try out this stuff though. Most of our database at work are 2000/2005 so I'm surprised I've not hit that before. I've removed the relevant bits from my answer.
Simon P Stevens
it's not obvious, but if you use procs or parametrisation then SQL won't see the string and convert, because it's already datetime
gbn