开发者

Whats the difference between these date where-clauses?

These two queries return different order counts and it's not entirely clear as to why. The first where clause is the accepted correct version:

where
year(OrderDate) = 2011
and MONTH(OrderDate) = 8
and DAY(OrderDate) = 3

but if I say something very similar:

开发者_StackOverflowWHERE 
io.OrderDate >= '2011-08-03 00:00:00' 
and io.OrderDate <= '2011-08-03 11:59:59'

I get a completely different record count. Is there something I'm doing wrong in date formatting or is there something I'm missing in logic? I'd prefer to say the latter as it's a little easier to use IMHO.


EDIT:

The new answer I would recommend combines my original (as displayed below) with the comments made by Mikael and Alex.

WHERE 
io.OrderDate >= '2011-08-03 00:00:00' 
and io.OrderDate < '2011-08-04 00:00:00'

Should provide the desired result.


The second query is only looking from Midnight to Noon. (00:00:00 - 11:59:59 is twelve hours)

WHERE 
io.OrderDate >= '2011-08-03 00:00:00' 
and io.OrderDate <= '2011-08-03 23:59:59'

Should fix it.

@Alex answer has a point as well. Milliseconds count (depending on whether or not your particular table includes them).

WHERE 
io.OrderDate >= '2011-08-03 00:00:00.000' 
and io.OrderDate <= '2011-08-03 23:59:59.999'

Would include any additional records missed


Well, 11:59:59 is just before midday (that's 11 am you're referrring to), which means you're missing 12 hours.

Also, keep in mind that you can also specify milliseconds in your DateTime. So you could have '2011-08-03 23:59:59.100', which is after your specified max OrderDate (even after correcting for 24 hour time)


You should do it like this.

WHERE 
io.OrderDate >= '2011-08-03 00:00:00' 
and io.OrderDate < '2011-08-04 00:00:00'

Apart from the fact that the rowcount is different in your queries, the first will not be able to use any index on OrderDate column.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜