创建while循环到CTE

时间:2013-12-02 11:55:18

标签: sql performance sql-server-2008-r2 common-table-expression

有人可以帮我创建这个循环进入CTE吗?我需要在很长的日期范围内运行它,并且需要一个年龄才能完成。

Declare @startdate datetime
Declare @enddate datetime

Set @startdate = convert(datetime,'2012-11-01 00:00:00',102)
Set @enddate = convert(datetime,'2013-11-28 23:59:00',102)

create table #Occupancy
(Occupancy numeric, 
 Startdate datetime)

DECLARE @StartDate2 Datetime
set @StartDate2 = @startdate

WHILE @StartDate2 <= @enddate

BEGIN

insert  #Occupancy
SELECT  count(*) as Occupancy, @StartDate2
from dbo.AAE_EPISODES_FROM_AMALGA as a
Left Join AAE_General as b
on a.AAEJoinKey = b.AAEJoinKey
Where   ((ARRIVAL_TIME <= CONVERT(DATETIME, @StartDate2, 102)) and (DischargeDateTime >= CONVERT(DATETIME, @StartDate2, 102)))

set @StartDate2 = DATEADD(hh,1,@StartDate2)

END

Select StartDate as Date, Occupancy
From  #Occupancy

0 个答案:

没有答案