We have all been in a situation where we had to get the last day of the month with T-SQL.To calculate if the last day is 31, 30, 28 or maybe even 29 is not that easy. There are many solutions to this problem out there, here is the one that i normally use:
DECLARE @myDate Datetime = '2012-02-12'SELECT DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, @myDate) +1, 0))
This code finds the difference in months, adds one month (this gives us the first day of the next month) and then substracts one day.
With the introduction of SQL Server Denali, we get a new function called EOMONTH. The EOMONTH takes two parameters the first one being the date and the next optional one being the number of months to add to the start date.
EOMONTH (start_date [, month_to_add]
DECLARE @myDate Datetime = '2012-02-12'SELECT EOMONTH (@myDate) AS Result;
DECLARE @myDate Datetime = '2012-02-12'SELECT DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, @myDate) +1, 0))
DECLARE @myDate Datetime = '2012-02-12'SELECT DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, @myDate) +1, 0))
This code finds the difference in months, adds one month (this gives us the first day of the next month) and then substracts one day.
With the introduction of SQL Server Denali, we get a new function called EOMONTH. The EOMONTH takes two parameters the first one being the date and the next optional one being the number of months to add to the start date.
EOMONTH (start_date [, month_to_add]
DECLARE @myDate Datetime = '2012-02-12'SELECT EOMONTH (@myDate) AS Result;
DECLARE @myDate Datetime = '2012-02-12'SELECT DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, @myDate) +1, 0))