I have a table which has a DATETIME column called dtInsertDate.
The value in this column is '2012-08-10 22:48:41.047'. I know that this date is 10th August 2012.
I want to run the following SELECT statement to retrieve this row:
select *
from myTable
where dtinsertdate = '2012-08-10 22:48:41.047'
The puzzling thing is, if I run this SELECT when the option dateformat is mdy, it finds that row.
If I run it on another copy of the database when the option dateformat is dmy, the SELECT doesn’t return anything.
Why is this ?
The reason is that dmy causes your string literal to be interpreted as day first – so that is October 8th instead of August 10th.
The solution is to always use an unambiguous format for date literals (or to use properly typed parameters instead of dealing with translating from a string in the first place).
As you’ve discovered, those dashes in your date can make the actual value be interpreted differently depending on language / dateformat settings.
Another alternative is to keep the dashes but to inject a T instead of a space, e.g.:
Your original is more readable, but it’s only guaranteed to work if you make the language and dateformat fixed (for example try with
SET LANGUAGE FRENCH;). Try this experiment:Sometimes the result is 8, sometimes the result is 10. Now try it again with one of the two formats I suggest above – result is always 8.
I have lots of juicy details worthy of reading here:
But for the specific problem you’re talking about, always, always, always use one of the following formats for date/time literals, I don’t consider any others safe.
For date + time:
For date only: