如何创建具有给定日期时间范围的日期表?

时间:2019-04-15 16:47:37

标签: sql-server tsql ddl

我正在尝试为日历创建表。但是sql server在'2000-01-11 17:45'处停止了。我该如何创建直到2050年增加15分钟的日期

Create Table Calendar
(id int IDENTITY(1,1) Primary key,CalendarDate DATETIME)


Declare @beginDate DATETIME, @endDate DATETIME
Select @beginDate = '2000-01-01 17:45', @endDate = '2050-01-01 09:00'


While @beginDate <= @endDate 
Begin
    Insert Into dbo.Calendar(CalendarDate)
    Select
        @beginDate As CalendarDate     

    Set @beginDate = DateAdd(MINUTE, 15, @beginDate)
End

1 个答案:

答案 0 :(得分:1)

您当前的语法建议为SQL Server,因此我将尝试递归CTE

with cte as (
      select @beginDate as  st
      union all
      select DATEADD(MINUTE, 15, st)
      from cte
      where st < @endDate

)

Insert Into dbo.Calendar(CalendarDate)
   select st as CalendarDate
   from cte
   option (maxrecursion 0);