我有一个简单的SQL Server 2008表,其列ourdate
类型为date
。
所以我尝试在日期值上应用between
,但它不起作用并给我一个错误。
Msg 241,Level 16,State 1,Line 1
转换日期和/或时间时转换失败
从字符串
这样的代码:
select *
from [ComplainsDb].dbo.dateTB
where ourdate between '2012-11-01' AND '2012-12-31';
答案 0 :(得分:3)
您需要为所有语言和区域设置使用安全的日期字符串格式。
ISO-8601格式YYYYMMDD
(注意:没有破折号!)适用于所有情况 - 试试这个:
select *
from [ComplainsDb].dbo.dateTB
where ourdate between '20121101' AND '20121231';
答案 1 :(得分:2)
尝试转换为日期,如下所示:
select *
from dateTB
where ourdate between convert(datetime,'2012-11-01') and convert(datetime,'2012-12-31');
select *
from dateTB
where convert(datetime,ourdate) between '2012-11-01' and '2012-12-31';
您也可以使用演员如下
select *
from dateTB
where ourdate between cast('2012-11-01' as datetime) and cast('2012-12-31' as datetime);
select *
from dateTB
where cast(ourdate as datetime) between '2012-11-01' and '2012-12-31';
答案 2 :(得分:1)
您需要将字符串转换为日期:
select *
from [ComplainsDb].dbo.dateTB
where ourdate between Cast('2012-11-01' AS Date) AND Cast('2012-12-31' AS Date);