March 28, 2008

Find Last Day Of a Month in SQL Server 2005

Let us see how to find out the last day of a month :

-- Return Last Date of a Month
DECLARE @Month smallint
SET @Month = 1
SELECT DATEADD(Month, DATEDIFF(Month,0,getdate())+@Month, -1) as LastDateOfMonth,
DAY(DATEADD(Month, DATEDIFF(Month,0,getdate())+@Month, -1)) as LastDayOfMonth

The @Month accepts the month that needs to be added as the third parameter of the DATEADD function. You can set different values as shown below to view the last day of the month

1 - Current Month
0 - Last Month
2 - Next Month


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

1 comment:

Anonymous said...

That function does not return the correct values at all.