Search code examples
sql-servert-sqlsql-server-2012recursive-queryrecursive-cte

How to get time from 00 to 23 using recursive CTE?


How do I get hours of a day from 00 hrs to 23 hrs using recursive CTE?

It gives hours 00 to 24, but I need to exclude the 24 hrs in my result set or in other words I need only up to 00 to 23 hrs

My Code:

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

It gives hours 00 to 24, but I need to exclude the 24 hrs in my result set or in other words I need only up to 00 to 23 hrs

Actual result:

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

Expected Result:

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

Solution

  • Instead of
    Select datediff(HOUR, @hr1Week, dateadd(DAY, 1, @hr1Week)), changing it to
    Select datediff(HOUR, @hr1Week, dateadd(DAY, 1, @hr1Week)) - 1
    will return the hours up to 23 only

    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