像Oracle一样按级别连接SQL Server 2008

时间:2012-07-17 12:26:57

标签: sql oracle sql-server-2008

nDays := Round( dEndTime - dStartTime ) + 1; 

For i in 1..7 Loop
 nDay := i + 1;
    if i = 7 Then
      nDay := 1;
    End If;

SELECT To_Date(To_Char((dStartTime+Level-1),'DD.MM.YYYY')||' 00:00','DD.MM.YYYY HH24:MI'),
To_Date(To_Char((dStartTime+Level-1),'DD.MM.YYYY')||' 23:59','DD.MM.YYYY HH24:MI')
FROM DUAL
WHERE To_Char( dStartTime + Level -1 , 'd' ) =  To_Char(nDay)
CONNECT BY Level <= nDays;

End Loop;

输出:

22-JUL-12
23-JUL-12
18-JUL-12
19-JUL-12
20-JUL-12
21-JUL-12

我需要将此查询转换为SQL Server 2008,请帮助找到相同的解决方法......

我已尝试使用nDay从1到7的单个查询输出上面的输出.....

1 个答案:

答案 0 :(得分:1)

您可以使用递归CTE执行此操作。但是,这种语法很难记住,所以当我需要一些项目时,我会做类似的事情:

select *
from (select row_number() over (order by (select NULL)) as seqnum
      from information_schema.columns
     ) t
where seqnum < <value>

可以使用任何表格。我只是放入INFORMATION_SCHEMA.columns表,因为它很容易,通常有几十行或几百行。

您的输出与查询不匹配。以下是两个合理靠近的值之间的所有日期,以下是一个示例:

declare @dstarttime date = '2012-07-11', @dendtime date=  '2012-07-13';
with const as (select @dstarttime as dStartTime, @dendtime as dendTime)
SELECT DATEADD(d, seqnum - 1, dStartTime)
FROM (select *
      from (select row_number() over (order by (select NULL)) as seqnum, const.*
            from information_schema.columns cross join const
           ) t
      where seqnum <= DATEDIFF(d, dStartTime, dendTime) + 1
     ) t

正如我所说,您也可以使用递归CTE或者如果有的话,使用日历表。