Search code examples
sqldatetimesql-server-2012

Select between two months


I'm trying to write a select query where my OrderDate is between two months. this is my code so far.

declare @FromMonth datetime
declare @ToMonth datetime
set @FromMonth = '20111201'
set @ToMonth = '20120301'

select *
from Order o
where o.OrderDate between @FromMonth and @ToMonth

This almost works, except that it also looks at the day of month, meaning in this example that it won't select all the days' in my @ToMonth

I'm using Sql Server 2012

EDIT

Just to make it more clear, I don't wanna trust my @FromMonth and @ToMonth input to know the last day in the month. The above is just a sample to illustrate my problem.


Solution

  • between rarely works as well as you might hope, I usually find it better to write the range as an inclusive/exclusive pair and apply appropriate comparisons:

    declare @FromMonth datetime
    declare @ToMonth datetime
    set @FromMonth = '20111201'
    set @ToMonth = '20120401'
    
    select *
    from Order o
    where o.OrderDate >= @FromMonth and o.OrderDate < @ToMonth
    

    This will also avoid nastiness if OrderDate includes a time component.