我有一个start_date和end_date。我想要得到这两个日期之间的日期列表。有人能帮我指出我的查询中的错误吗?

select Date,TotalAllowance 
from Calculation 
where EmployeeId=1
  and Date between 2011/02/25 and 2011/02/27

这里Date是一个datetime变量。


当前回答

试着把日期放在# #之间 例如:

#2013/4/4# and #2013/4/20#

这对我很管用。

其他回答

实际上,为了得到最准确的结果,所有sql日期都应该是yyyy-MM-dd格式。

如果日期在24小时内,从早上开始,到晚上结束,应该添加如下内容:

declare @Approval_date datetime
set @Approval_date =getdate()
Approval_date between @Approval_date +' 00:00:00.000' and @Approval_date +' 23:59:59.999'

我会选择

select Date,TotalAllowance from Calculation where EmployeeId=1
             and Date >= '2011/02/25' and Date < DATEADD(d, 1, '2011/02/27')

逻辑是>=包括整个开始日期,<不包括结束日期,因此我们在结束日期上添加一个单位。这可以适应几个月,例如:

select Date, ... from ...
             where Date >= $start_month_day_1 and Date < DATEADD(m, 1, $end_month_day_1)
select Date,TotalAllowance 
from Calculation 
where EmployeeId=1
  and convert(varchar(10),Date,111) between '2011/02/25' and '2011/02/27'
select * from test 
     where CAST(AddTime as datetime) between '2013/4/4' and '2014/4/4'

——如果数据类型不同