2

我在 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 循环填充一个表变量,并在我的存储过程中进一步使用这个表变量来加入其他表。但我想避免使用临时表或表变量。有没有什么方法可以在没有任何迭代或循环的情况下通过选择查询获得相同的结果(通过 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
4

1 回答 1

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);

或者

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
于 2013-10-31T07:34:45.543 回答