如果我通过了日期,即2020年4月20日,为什么程序会出错



我正在使用这个

CAST(NotifDate as date) between @FromNotifDate AND @ToNotifDate

但表中的NotifDate保存为varchar,但FromNotifDateToNotifDate[/strong>属于

Date当我通过这些参数08/06/2014 and 20/04/2020 09:40:17时,它不起作用,并抛出错误,即

从字符串转换日期和/或时间时转换失败。

但如果我通过08/06/2014 and 10/04/2020 09:40:17,它就可以工作了。

您当前的数据库区域设置可能设置为en-US或其他日期格式为MM/dd/yyyy的设置。

这使得08/06/201410/04/2014的有效日期(但它们是8月6日和10月4日,不是6月8日和4月10日!(,但不是20/04/2020

要使用不同的日期格式,您可以使用CONVERT,并使用正确的样式代码(我相信dd/MM/yyyy是103(请参阅文档(

因此,这应该适用于您:CONVERT(date, NotifDate, 103)

请注意,作为一般建议,如果可能的话,首先在数据库中输入NotifDate作为正确的SQL日期是有益的,以避免在查询中进行这样的转换。

此外,还有明确的国际标准ISO-8601格式yyyy-MM-ddCAST应该始终正确解析它,我建议在代码基础结构中尽可能使用它而不是任何本地化格式。

默认日期格式为"MM/dd/yyyy"的系统,因此当您设置"10/04/2020 09:40:17"值时,系统会出现错误-超出范围错误,

-- The conversion of a varchar data type 
-- to a datetime data type resulted in an out-of-range value.
select cast('20/04/2020 09:40:17'  as datetime)     
-- get the current session date_format
select date_format
from sys.dm_exec_sessions
where session_id = @@spid
-- set the dateformat for the current session
set dateformat dmy
-- this should work
select cast('20/04/2020 09:40:17'  as datetime)

最新更新