我正在尝试根据sql server中的两个日期获取记录...
Select * from table where CreatedDate between @StartDate and @EndDate
我传递5/12/2010
和5/12/2010
(即)获取今天的记录...我有17条记录5/12/2010
,但似乎没有被选中.... < / p>
修改
我使用它,但是当我调试我的值时,它会显示5/12/2010 12:00:00AM
DateTime baseDate = DateTime.Today;
var today = baseDate;
GetBookingReportByDate(today,today);
我在c#中使用这些,以及以startdate
和lastdate
为参数的可重复使用的存储过程,
DateTime baseDate = DateTime.Today;
var today = baseDate;
var yesterday = baseDate.AddDays(-1);
var thisWeekStart = baseDate.AddDays(-(int)baseDate.DayOfWeek);
var thisWeekEnd = thisWeekStart.AddDays(7).AddSeconds(-1);
var lastWeekStart = thisWeekStart.AddDays(-7);
var lastWeekEnd = thisWeekStart.AddSeconds(-1);
var thisMonthStart = baseDate.AddDays(1 - baseDate.Day);
var thisMonthEnd = thisMonthStart.AddMonths(1).AddSeconds(-1);
var lastMonthStart = thisMonthStart.AddMonths(-1);
var lastMonthEnd = thisMonthStart.AddSeconds(-1);
我使用这些值并仅根据startdate和lastdate获取记录...完全像stackoverflow Today,Yesterday,this week, last week,this month,Last month
....
答案 0 :(得分:4)
您没有包含时间部分...因此两者都被解析为相同的值。
你需要:
SELECT *
FROM Table
WHERE CreatedDate >= '5/12/2010 00:00:00'
AND CreatedDate <= '5/12/200 23:59:59'
或者:
SELECT *
FROM Table
WHERE CreatedDate >= @StartDate
AND CreatedDate <= DATEADD(day, 1, @StartDate)
<强>更新强>
看到您的更新后,像我的第二个示例更改查询仍然有效。您也可以在C#代码中进行更改:
GetBookingReportByDate(today, today.AddDays(1));
答案 1 :(得分:2)
问题是SQL正在比较日期和时间。因此,您查询转换为CreatedDate Between '2010-05-12 00:00:00.000' And '2010-05-12 00:00:00.000'
。相反,你应该做类似的事情:
CreatedDate >= @StartDate And CreatedDate < DateAdd(d,1,@EndDate)
。
答案 2 :(得分:1)
请改为尝试:
Select *
from table
where CreatedDate >= @StartDate
and CreatedDate < @EndDate
并将@EndDate设为“明天”
答案 3 :(得分:0)
如果您不想更改sql语句,可以像这样更改C#:
GetBookingReportByDate(today,today.AddDays(1));