递归CTE混淆

时间:2014-10-09 22:18:36

标签: sql sql-server

今天早些时候的帖子让我想到了使用递归CTE。基本上,我们的目标是拥有一个小时和15分钟增量的简单表格,如下所示:

HOUR   MINUTE
1      15
1      30
1      45
1      60
2      15
2      30
...

这似乎是递归CTE的好机会。但是,当我尝试在CTE中执行这两个部分时,它只是永远运行,吐出无限数量的行。

with 
cteMin as (
  select 15 as mnt
  union select 30
  union select 45
  union select 60),
cte
as (
select 1 as hour
  ,0 as mnt
union all
select 
hour + 1,
cteMin.mnt
from cte
cross join cteMin 
where hour < 24

)

select * from CTE

如果我将分钟部分向下移动为派生查询,则表现良好,返回96行。

with cte as 
( select 1 as theHour
union all
select theHour + 1
from cte
where theHour <24)

select * from cte 
cross join
(select 15 as theMin
union select 30
union select 45
union select 60) as Mins

我错过了什么,或做错了什么?因为在这一点上,这对我来说毫无意义。

0 个答案:

没有答案