用Select查询替换While循环

时间:2013-10-31 07:24:12

标签: sql sql-server-2008 select replace while-loop

我在SQL Server 2008中有以下SQL语句

DECLARE @Interval table(StartInterval DATETIME,
            EndInterval   DATETIME ) 


        WHILE (DATEADD(mi,1440,@STARTDATE) <= @ENDDATE)
        BEGIN
          INSERT INTO @Interval
            SELECT @STARTDATE, DATEADD(mi,1440,@STARTDATE)

          SET @STARTDATE = DATEADD(mi,1440,@STARTDATE)
        END

@StartDate和@EndDate是两个参数。我使用while循环填充表变量,并在我的存储过程中进一步使用此表变量与其他表连接。但我想避免临时表或表变量。有没有什么办法可以在没有任何迭代或循环的情况下使用select查询获得相同的结果(使用while循环实现)?所以我可以做点像

Select * from (logic that replace while loop) Result inner join some table on col1=col2

期望的结果

 StartInterval          EndInterval
2013-10-25 00:00:00.000 2013-10-26 00:00:00.000
2013-10-26 00:00:00.000 2013-10-27 00:00:00.000
2013-10-27 00:00:00.000 2013-10-28 00:00:00.000

1 个答案:

答案 0 :(得分:6)

请尝试使用CTE:

declare @StartInterval datetime, @EndInterval   datetime
select @StartInterval='01-June-2013', @EndInterval   =GETDATE();

with T as (
    select 
        @StartInterval as StartInterval, 
        DATEADD(mi, 1440, @StartInterval) EndInterval
    union all
    SELECT 
        EndInterval, DATEADD(mi,1440,EndInterval)
    FROM T
    WHERE 
        EndInterval <= @EndInterval
)select * from T
OPTION (MaxRecursion 0);

OR

select StartInterval, DATEADD(mi, 1440, StartInterval) EndInterval
from(
    select DATEADD(mi, (ROW_NUMBER() OVER (ORDER BY OBJECT_ID)-1)*1440, @StartInterval) StartInterval
    FROM master.sys.all_columns 
)x where StartInterval <=@EndInterval