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

问题描述 投票:1回答:1

我正在尝试为calendar创建一个表。但是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
sql-server tsql ddl
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.