如何使用递归CTE将时间从00变为23?

时间:2019-05-15 05:45:07

标签: sql-server tsql sql-server-2012 recursive-query recursive-cte

如何使用递归CTE获得每天从00到23个小时的时间?

它提供00到24小时,但是我需要在结果集中排除24小时,换句话说,我最多只需要00到23小时

我的代码:

DECLARE @calenderDate DATETIME2(0) = '2019-05-16 05:00:00'
DECLARE @hr1Week int = 0

;with numcte AS  
       (  
         SELECT 0 [num]  
         UNION all  
         SELECT [num] + 1 FROM numcte WHERE [num] < (Select  datediff(HOUR, @hr1Week, dateadd(DAY, 1, @hr1Week)))
       )        

select * from numcte

它提供00到24小时,但是我需要在结果集中排除24小时,换句话说,我最多只需要00到23小时

实际结果:

num
----
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

预期结果:

num
---
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

1 个答案:

答案 0 :(得分:2)

代替
Select datediff(HOUR, @hr1Week, dateadd(DAY, 1, @hr1Week)),将其更改为
Select datediff(HOUR, @hr1Week, dateadd(DAY, 1, @hr1Week)) - 1
将只返回最多23小时的小时数

DECLARE @calenderDate DATETIME2(0) = '2019-05-16 05:00:00'
DECLARE @hr1Week int = 0

;with numcte AS  
(  
     SELECT 0 [num]  
     UNION all  
     SELECT [num] + 1 FROM numcte WHERE [num] < 
      (SEELCT datediff(HOUR, @hr1Week, dateadd(DAY, 1, @hr1Week)) -1)
)        

SELECT * FROM numcte

Demo on db<>fiddle