【问题标题】:How to create date table with given datetime range?如何创建具有给定日期时间范围的日期表?
【发布时间】:2019-04-15 16:47:37
【问题描述】:

我正在尝试为日历创建一个表。但是 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,753,214 行。您的查询是否超时?我认为您的问题出在其他地方。
  • 我解决了这个问题,谢谢。

标签: sql-server tsql ddl


【解决方案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);

【讨论】:

  • 查询于 2000-01-22 03:30:00.000 停止
  • 很抱歉没有。我选择了前 1000 名
猜你喜欢
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多