我正在使用这个
CAST(NotifDate as date) between @FromNotifDate AND @ToNotifDate
但表中的NotifDate保存为varchar,但FromNotifDate和ToNotifDate[/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/2014
和10/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-dd
,CAST
应该始终正确解析它,我建议在代码基础结构中尽可能使用它而不是任何本地化格式。
默认日期格式为"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)