Datetime conversion error for 1 sql server, but not another

让人想犯罪 __ 提交于 2019-11-28 08:55:46

问题


I've got 2 servers running SQL Server 2008, and I have the following query:

SELECT cast('13/1/2011' as datetime)

If I execute this query on Server A I get the result:

2011-01-13 00:00:00.000

However, if I execute this on Server B I get the result:

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

I believe this to be a UK/US date format issue as I don't get an error with 12/1/2011 but it does return 2011-12-01 00:00:00.000

How can I get Server B to get the same result as Server A? What setting needs to be changed and where?


回答1:


It is the language setting of the login that controls how these ambiguous date formats are interpreted (though this can be overridden with an explicit SET DATEFORMAT statement).

The DEFAULT_LANGUAGE can be changed via ALTER LOGIN




回答2:


Even better, don't rely on the SET DATEFORMAT or DEFAULT_LANGUAGE settings to ensure your date conversions work as expected. In SQL Server one should always—as a matter of best practice—either use a neutral format, or use an explicit format specifier, no matter what language settings are in use or what your dates look like. Try the following on both servers and you will have no problem.

  • Date neutral format: Convert(datetime, '20110113')
  • Date neutral format: Convert(datetime, '2011-01-13T00:00:00')
  • Explicit format specifier: Convert(datetime, '13/1/2011', 103) - see SQL Server Books Online: Cast and Convert for details.


来源:https://stackoverflow.com/questions/8053901/datetime-conversion-error-for-1-sql-server-but-not-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!