Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Ottieni ogni ora per un intervallo di tempo

Non sono richiesti loop, CTE ricorsivi o tabelle numeriche.

DECLARE 
  @start TIME(0) = '11:00 AM', 
  @end   TIME(0) =  '2:00 PM';

WITH x(n) AS 
(
  SELECT TOP (DATEDIFF(HOUR, @start, @end) + 1) 
  rn = ROW_NUMBER() OVER (ORDER BY [object_id]) 
  FROM sys.all_columns ORDER BY [object_id]
)
SELECT t = DATEADD(HOUR, n-1, @start) FROM x ORDER BY t;