Reputation: 1568
I want to generate a list of hours between to hours with an interval of 30 minutes.
For example an employee enters work at 09:00 and leaves at 18:00, so I want to generate this:
Hours
-----
09:00
09:30
10:00
10:30
11:00
11:30
12:00
12:30
13:00
13:30
14:00
14:30
15:00
15:30
16:00
16:30
17:00
17:30
18:00
How can I generate this? Thanks.
Upvotes: 2
Views: 237
Reputation: 317
You can also try while loop
DECLARE @strattime TIME = '09:00' DECLARE @endtime TIME = '18:00' CREATE TABLE #tmp_hours( [BetweenHours] VARCHAR(5) ) WHILE @strattime <= @endtime BEGIN INSERT INTO #tmp_hours values(@strattime) SET @strattime = DATEADD(minute,30,@strattime) END SELECT * FROM #tmp_hours DROP TABLE #tmp_hours
Upvotes: 1
Reputation: 44316
This will give you what you need, using a tally is faster than recursive:
DECLARE @from time = '09:00'
DECLARE @to time = '09:00'
IF @from <= @to
WITH N(N)AS
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
SELECT top (datediff(minute, @from, @to)/ 30 + 1 )
LEFT(dateadd(minute, (N - 1 )*30, @from), 5)
FROM tally
Upvotes: 4
Reputation: 6656
Well using recursive CTE, you can achieve this result.
Try below query -
DECLARE @timeFrom TIME = '09:00'
DECLARE @timeTo TIME = '18:00'
;with SourceHrs
as
(
select @timeFrom as [Hours]
UNION ALL
SELECT DATEADD(MINUTE, 30, [Hours]) from SourceHrs WHERE [Hours] < @timeTo
)
SELECT CONVERT(VARCHAR(5),Hours,108) FROM SourceHrs
Result
Hours
-------
09:00
09:30
10:00
10:30
11:00
11:30
12:00
12:30
13:00
13:30
14:00
14:30
15:00
15:30
16:00
16:30
17:00
17:30
18:00
Upvotes: 6