Calculating the Previous Month’s Date Range in SQL

Here’s a handy snippet that calculates the start and end dates for the previous month based on the current date. I find this very handy when I have an automated script that reports on the figures for only the last month.

DECLARE @LastMonth AS smalldatetime
DECLARE @LastMonthStart AS smalldatetime
DECLARE @LastMonthEnd AS smalldatetime

-- Move back one month from today's date
SET @LastMonth = DATEADD(month, -1, GETDATE())

-- Use the year and month components but set the day to be the 1st
SET @LastMonthStart = CAST(YEAR(@LastMonth) AS varchar) + '-' + CAST(MONTH(@LastMonth) AS varchar) + '-01'

-- The end date should be exactly one month from the start date
SET @LastMonthEnd = DATEADD(month, 1, @LastMonthStart)

-- Typical usage
...WHERE [DateColumn] >= @LastMonthStart AND [DateColumn] < @LastMonthEnd
Advertisements
This entry was posted in Tips and Tricks and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s