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

后端 未结 11 548
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 05:21

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 firs

11条回答
  •  萌比男神i
    2020-11-30 05:53

    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.

提交回复
热议问题