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
- Add a month in the given date by using DateAdd function. It will become 17-April-2007
- Get the Day part of the date from the above step. It is 17
- Subtract number of days of the second step from the date of step 1. It will become 31-March-2007
- 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