Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to populate a temp table with dates between and including 2 date parameters

Tags:

What is the easiest way to populate a temp table with dates including and between 2 date parameters. I only need the 1st day of the month dates.

So for example if @StartDate = '2011-01-01' and @EndDate = '2011-08-01'

Then I want this returned in the table

2011-01-01 2011-02-01 2011-03-01 2011-04-01 2011-05-01 2011-06-01 2011-07-01 2011-08-01 
like image 235
mameesh Avatar asked Oct 18 '11 20:10

mameesh


People also ask

How do I pass between two dates in SQL?

SELECT * FROM ATM WHERE TRANSACTION_TIME BETWEEN '2001-02-01 10:00:00' AND '2007-03-01 22:00:00';

Does between work with dates in SQL?

The SQL BETWEEN Operator The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.

How do I populate a date in a table in SQL?

You can use an auxiliary table of numbers (Itzik's VATN is a nice one), a recursive cte, etc, and of course a calendar table as suggested by Arbi. Thanks v. vt, that did the trick. Please learn to use the ISO-8601 date format.


1 Answers

This works even if the @StartDate is not the first of the month. I'm assuming that if it's not the start of the month, you want to begin with the first of the next month. Otherwise remove the +1.:

;WITH cte AS ( SELECT CASE WHEN DATEPART(Day,@StartDate) = 1 THEN @StartDate              ELSE DATEADD(Month,DATEDIFF(Month,0,@StartDate)+1,0) END AS myDate UNION ALL SELECT DATEADD(Month,1,myDate) FROM cte WHERE DATEADD(Month,1,myDate) <=  @EndDate ) SELECT myDate FROM cte OPTION (MAXRECURSION 0) 
like image 177
GilM Avatar answered Oct 18 '22 21:10

GilM