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

There are some times where database applications give the above error when trying to convert strings to the datetime format in SQL Server.

This error is related to the default language and consequently the dateformat used by the corresponding SQL Server login.

There are two approaches for avoiding/resolving this issue. The first approach is to include the necessary logic in your database application in order not to depend on the default language setting, but use the ISO date format which is: yyyy-mm-dd hh:nn:ss.

The second approach is to change the default language setting for the specific SQL Server login to "us_english".

By executing the following script in SQL Server you get a list with all the logins and among others, the default language names used by these logins. The relevant column name in the results of this script is the "DefLangName":

--Query that changes the default language to "us_english" for a given SQL Server login:
use [master]
EXEC sp_helplogins
GO

If the default language name for the specific login is different than "us_english", and your application's code does not explicitly handle these date-conversion issues, there is the possibility of getting the conversion error when executing your application. You can easily change this setting to "us_english" by executing the below script:

--Query that changes the default language to "us_english" for a given SQL Server login:
use [master]
ALTER LOGIN "LOGIN_NAME" WITH DEFAULT_LANGUAGE = us_english;
GO

* You have to change the "LOGIN_NAME" string to the desired login name for which you would like to change its default language setting.

* You can also change this setting through SQL Server Management Studio.

Concluding, the safest way to handle dateformat data in database applications, is to setup the default language setting for the relevant SQL Server login to "us_english" and use parameterized queries in your source code. To this end, the date formatting will be automatically handled thus avoiding possible conversion errors.

Hope this helps.

Labels: ,