I have two date for example 08/08/2013 and 11/11/2013 and I need last date of each month starting from August to November in a table so that i can iterate over the table to pick those dates individually.
I know how to pick last date for any month but i am stucked with a date range.
kindly help, it will be highly appreciated.
Note : I am using Sql 2008 and date rang could be 1 month , 2 month or 6 month or a year or max too..
I've created a table variable, filled it with all days between
@startDate
and@endDate
and searched for max date in the month.Results:
To also get last day of November this can be used before loop:
You can use a recursive CTE to do this, note the
MAXRECURSION
OPTION
prevents an infinite loop:This returns
The following CTE gives you the last day of every month from February 1900 until the middle of the 26th century (on my machine):
It should be easy enough to use it as part of a larger query or to filter it down to just the dates you want. You can adjust the range of years as needed by changing the constant
19000131
. The only important thing to do is make sure that you use a month that has 31 days in it and always have the constant be for day 31.