Search code examples
sqlt-sqlstored-proceduressql-server-2000

How can I generate a temporary table filled with dates in SQL Server 2000?


I need to make a temporary table that holds of range of dates, as well as a couple of columns that hold placeholder values (0) for future use. The dates I need are the first day of each month between $startDate and $endDate where these variables can be several years apart.

My original sql statement looked like this:

select dbo.FirstOfMonth(InsertDate) as Month, 0 as Trials, 0 as Sales
into #dates
from customer
group by dbo.FirstOfMonth(InsertDate)

"FirstOfMonth" is a user-defined function I made that pretty much does what it says, returning the first day of the month for the provided date with the time at exactly midnight.

This produced almost exactly what I needed until I discovered there were occasionally gaps in my dates where I had a few months were there were no records insert dates. Since my result must still have the missing months I need a different approach.

I have added the following declarations to the stored procedure anticipating their need for the range of the dates I need ...

declare $startDate set $startDate = select min(InsertDate) from customer
declare $endDate set $endDate = select max(InsertDate) from customer

... but I have no idea what to do from here.

I know this question is similar to this question but, quite frankly, that answer is over my head (I don't often work with SQL and when I do it tends to be on older versions of SQL Server) and there are a few minor differences that are throwing me off.


Solution

  • This will quickly populate a table with 170 years worth of dates.

    CREATE TABLE CalendarMonths (
      date DATETIME,
      PRIMARY KEY (date)
    )
    
    DECLARE
      @basedate DATETIME,
      @offset   INT
    SELECT
      @basedate = '01 Jan 2000',
      @offset = 1
    
    WHILE (@offset < 2048)
    BEGIN
      INSERT INTO CalendarMonths SELECT DATEADD(MONTH, @offset, date) FROM CalendarMonths
      SELECT @offset = @offset + @offset
    END
    

    You can then use it by LEFT joining on to that table, for the range of dates you require.