【问题标题】:Replacing While loop with Select query用 Select 查询替换 While 循环
【发布时间】:2013-11-11 02:31:20
【问题描述】:

我在 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

【问题讨论】:

  • 查看递归 CTE。您可能会发现使用它的一些性能优势。

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


【解决方案1】:

请尝试使用 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

【讨论】:

  • :太好了。我怎样才能将这个结果与其他表连接起来? like Select * from table1,(CTE 的结果)
  • 你可以把它当成table,在join中使用select * from T INNER JOIN T1 on T.Col=T1.Col
猜你喜欢
  • 2016-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 2013-03-11
相关资源
最近更新 更多