2009-11-03 57 views
0

使用SQL Server 2005如何重複這兩個日期之間的值?

我想這兩個日期

之間產生的表值表1

ID Date  Intime Outtime 

01 12-02-2009 10:00:00 17:00:00 
02 13-02-2009 08:00:00 16:00:00 
03 14-02-2009 09:00:00 21:00:00 
04 15-02-2009 

假設我要產生兩個日期之間的上述表中的值。

例如,

給定日期:開始日期 - 12-02-2009結束日期 - 2009年12月3日

預計輸出,

ID Date  Intime Outtime 

01 12-02-2009 10:00:00 17:00:00 
02 13-02-2009 08:00:00 16:00:00 
03 14-02-2009 09:00:00 21:00:00 
04 15-02-2009 
05 16-02-2009 10:00:00 17:00:00 
06 17-02-2009 08:00:00 16:00:00 
07 18-02-2009 09:00:00 21:00:00 
08 19-02-2009 
09 20-02-2009 10:00:00 17:00:00 
…, 

所以從表1,我們有4行,所以4行將重複到給定的結束日期,但id和日期應該增加,id和日期不應該重複。

如何爲這種情況製作SQL查詢?

需要查詢幫助。

回答

2

試試這個太...

declare @startdate datetime 
    declare @enddate datetime 

    set @startdate = '12-02-2009' 
    set @enddate = '12-05-2009' 

    ;with num_cte as 
    (
      select top(datediff(day,@startdate,@enddate)) ROW_NUMBER() OVER (ORDER BY c.column_id) AS rn 
      from sys.columns c 
    ) 
    , generate_date_cte as 
    ( 
      select 1 as Id,@startdate as newdate 
      union all 
      select rn+1 as Id, newdate 
      from num_cte 
      cross apply(select DATEADD(day,rn,@startdate) AS newdate) x 
    ) 
    select * from generate_date_cte 
0

試試這個

declare @startdate datetime 
declare @enddate datetime 

set @startdate = '12-02-2009' 
set @enddate = '12-05-2009' 

;with generateCalender_cte as 
(
select 
1 as Id 
,@startdate DateValue 
union all 
select 
c.Id + 1    
    ,DateValue + 1 
from generateCalender_cte c 
where DateValue + 1 <= @enddate 
) 

select * from generateCalender_cte 
0

另一種解決方案

declare @startdate datetime 
    declare @enddate datetime 

    set @startdate = '12-02-2009' 
    set @enddate = '12-05-2009' 

    ; with generateCalender_cte as 
    (
      select 
      1 as Id 
      ,@startdate as newdate 
      union all 
      select 
      c.Id + 1 
      ,DATEADD(day,1,c.newdate) 
      from generateCalender_cte c 
      where c.newdate <@enddate 
    ) 
    select * from generateCalender_cte 
相關問題