SQL Tips by Namwar Rizvi

June 26, 2007

T-SQL DATETIME : Last Day of the Month

Filed under: Query,tips,TSQL,UDF,Utility Functions — namwar @ 10:29 PM

Getting the last day of the month, for the given date, by TSQL is bit tricky. Following user defined function provides you a handy general purpose function to get the last day of the month.
It gets the last day of the month as follows:
For example we have a given date 17-March-2007

  1. Add a month in the given date by using DateAdd function. It will become 17-April-2007
  2. Get the Day part of the date from the above step. It is 17
  3. Subtract number of days of the second step from the date of step 1. It will become 31-March-2007
  4. Resulting date in step 3 is our answer.

Following is the TSQL code of the function

Create function
udf_GetLastDayOfTheMonth(@m_GivenDate datetime)

returns datetime
as
Begin

Return dateadd(day,-1* day(dateadd(month,1,@m_GivenDate)),dateadd(month,1,@m_GivenDate))

End

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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

Blog at WordPress.com.

%d bloggers like this: