A user asked me how to find the first day of the previous and next month in SQL Server. It’s quite simple as explained in Itzik’s excellent book Inside Microsoft SQL Server 2008: T-SQL Programming (Pro-Developer).
Here’s the query
Here’s the same query to try out:
-- To Get First Day of Previous Month
SELECT DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - 1, '19000101')
as [First Day Previous Month];
GO
-- To Get First Day of Next Month
SELECT DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) + 1, '19000101')
as [First Day Next Month];
GO
To understand what we just did, first execute the following query:
SELECT DATEDIFF(MONTH, '19000101', GETDATE())
This query returns 1333 (as of this writing) which is the number of months since 1/1/1900. Since we want to calculate a day of the previous month, subtract 1. To calculate a day of the next month, add 1. That’s it, now use the DATEADD function to return a specified date with the number interval (1333) subtracted or added to the datepart (month) of 1/1/1900.
OUTPUT
You may also want to check
SQL Server: First and Last Sunday of Each Month
Find First and Last Day of the Current Quarter in SQL Server
1 comment:
DECLARE @PreviousMonthStart DATETIME
DECLARE @PreviousMonthEnd DATETIME
SET @PreviousMonthStart = DATEADD(m,DATEDIFF(m,0,GETDATE())-1,0)
SET @PreviousMonthEnd = DATEADD(ms,-2,DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0))
PRINT @PreviousMonthStart
PRINT @PreviousMonthEnd
SELECT * FROM MyTable
WHERE MyDate >= @PreviousMonthStart
AND MyDate < @PreviousMonthEnd
Post a Comment