Technical Article

Last Day of Month

,

A script was recently published (Last_Date_Of_Month) that returns the last day of a given month/year combination. I have simplified and improved on that script by eliminating the need to use a WHILE loop. This new script exploits the flexibility of the DATEADD function which allows you to assign negative numbers (thus effectively subtracting a given date element from the entered date). By setting the date format explicitly the script is also guaranteed to work for all locales. There is certainly no performance gain but I think it's a litte more elegant!

DECLARE @MonthINT
DECLARE @YearINT
DECLARE @DateSMALLDATETIME

SET@Month = 2
SET@Year = 2012

SETDATEFORMAT ymd

SET@Date = CAST(@Year AS CHAR(4)) + '/' +  RTRIM(CAST((@Month) AS CHAR(2))) + '/01' 
SET@Date = DATEADD(m, 1, @Date)
SELECTDAY(DATEADD(d, -1, @Date))

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating