• There are easier ways to get "last month" and such type dates.

    Take a look at this:

    SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)AS FirstOfCurrentMonth,

    DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0)AS FirstOfPriorMonth,

    DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0)AS FirstOfCurrentYear

    What it does is use DateDiff to get the number of months from "date zero" to today, and then adds that number of months to "date zero". In a default SQL Server installation, "date zero" is 1 Jan 1900, but it doesn't really matter what date it is set to, since the difference and addition will still get the same result. The second one gets the prior month by simply subtracting 1 from the difference, and the last one uses years instead of months to get the first day of the current year. Yes, getting the first day of the year is trivial, this is just meant to show how to extend the technique.

    So, if you need to check if a date is from last month, use the second calculation to get the first date, and the first calculation to get the last date of that range, and then use the usual greater-than-or-equal-to for the first, and less-than for the end, and you have it.

    Because of the way SQL Server stores dates (as numbers), and because of the way DateAdd and DateDiff work, this technique is much faster than anything else I've seen for this kind of thing.

    Because it's simple math once you know what the functions do, it's easy to get it to generate ranges like "last 6 months" (just use -6 instead of -1 in the "last month" version), or "last quarter" (use quarters instead of months/years in the functions), or whatever you need date-wise.

    - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
    Property of The Thread

    "Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon