declare @str_datetime varchar(50)
set @str_datetime='30-04-2012 19:01:45' -- 30th April 2012
declare @dt_datetime datetime
select @dt_datetime=@str_datetime
This is giving following error:
Msg 242, Level 16, State 3, Line 4
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
My question is how SQL Server decides which format to use for implicit datetime conversion?
This can depend on a variety of factors - the operating system's regional settings, the current user's language and dateformat settings. By default, Windows uses
US English
, and the user's settings areUS English
andMDY
.But here are some examples to show how this can change.
User is using BRITISH language settings:
(Error)
User is using Français:
(Error)
User is again using Français:
(Error)
User is using DMY instead of MDY:
(Error)
Your best bet, always, is to use ISO standard, non-regional, safe, unambiguous date formats. The two I typically recommend are:
None of these fail:
Therefore, I strongly recommend that instead of letting users type in free text date formats (or that you use unreliable formats yourself), control your input strings and make sure they adhere to one of these safe formats. Then it won't matter what settings the user has or what the underlying regional settings are, your dates will always be interpreted as the dates they were intended to be. If you are currently letting users enter dates into a text field on a form, stop doing that and implement a calendar control or at least a pick list so you can ultimately control the string format that is passed back to SQL Server.
For some background, please read Tibor Karaszi's "The ultimate guide to the datetime datatypes" and my post "Bad Habits to Kick : Mis-handling date / range queries."
Source
So you what you need to do is set date format before hand as so:
And then your query will work.
You can also change de default date format for each logins and/or for each future added logins (without the needs to do "SET DATEFORMAT" in each session.
You go in SQL Management Studio / Security / Logins. Right-clic the login, then Properties. You will see "Default Language" at the bottom.
If you want to make sure any logins added in the future get the "good" language. You right-click on your server root, then Properties and Advanced page. There is an option "Default Language" there too that is used to newly created logins.