February 22, 2011

SQL Server: First Day of Previous Month




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

first day SQL Server

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

SQL Server first day 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


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

0 Responses to "SQL Server: First Day of Previous Month"
 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions