根据表格自动生成日期

时间:2017-03-11 03:55:54

标签: sql sql-server

我在SQL server中有一个表

enter image description here

我想在StartDate和EndDate之间生成每个演示日。通常,我必须创建一个脚本,声明一个游标并循环遍历游标以创建每个单独的日期。但是使用游标会大大减慢速度。

我想知道是否有人有更好的想法使用加入

我成功地根据startdate和enddate生成日期

SELECT d."CalendarDay"                     AS "PresenttionDate",
   DATEPART(dw,d."CalendarDay")            AS "PresentationDay"
FROM
   (
     SELECT StartDate-1+number AS "CalendarDay"
     FROM master..spt_values
     where type='P' and number<= DateDiff(day,StartDate,EndDate) 
   )d

我只是不知道如何将StartDate和EndDate绑定到演示文稿表。

基本上,我正在寻找下面的最终结果:

enter image description here

不涉及光标。那可能吗?

请告知。

1 个答案:

答案 0 :(得分:2)

我认为这已足够:

with n as (
      select row_number() over (order by (select null)) - 1 as n
      from master..spt_values
     )
select t.*, dateadd(day, n.n, t.startDate) as thedate
from t join
     n
     on dateadd(day, n.n, t.startDate) <= t.endDate;
相关问题