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.
答案 0 :(得分:6)
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
答案 1 :(得分:4)
这将为您提供所需,使用计数比递归更快:
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
答案 2 :(得分:2)
您还可以尝试while循环
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