我运行了以下查询:
dbcc useroptions
它告诉我的 dateformat
设置是 mdy
。
然后我在 SQL Server Management Studio (SSMS) 中运行以下查询,该查询成功运行:
declare @mydate as datetime
set @mydate = '07-29-2017' -- 'mdy' formatted date string corresponding to 29 August, 2017
select @mydate
现在,我运行了以下查询:
declare @mydate as datetime
set @mydate = '29-07-2017' --here the format is dmy so SQL Server fails to parse it
select @mydate
上述查询导致以下错误:
Msg 242, Level 16, State 3, Line 5 The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
这个错误对我来说是可以接受的,因为日期格式不匹配。但是,当我运行下面的查询时,它成功了:
declare @mydate as datetime
set @mydate = '2017-07-29' -- this ymd format is also conflicting with mdy setting but it succeeds
select @mydate
那么,我想了解 SQL Server 解析任何字符串日期时间的能力是否完全取决于 useroptions
中的这个 dateformat
设置?如果是,那么为什么 ISO 8601 日期格式 yyyy-MM-dd 字符串日期能够成功解析?如果不是,那么成功解析的驱动设置/原因是什么?
最佳答案
这在 SQL Server 中始终有效:
set @mydate = '20170729'
无论国际化设置如何(如 here 所述)。这并不能完全回答您的问题,但它指出 dateformat
并不包含全部内容。
我怀疑带有连字符的版本被接受是出于利他主义(SQL Server 识别年份为第一)或者因为它与 ODBC 格式非常相似。
关于sql - 为什么即使用户登录的日期格式设置设置为 'yyyy-mm-dd',ISO 8601 日期格式 'mdy' 字符串文字仍然有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45385026/