Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

sql - Get every hour for a time range

So what I am trying to is generate all the hours that are inside a specific time range.

So given the range 11 AM to 2:00 PM, I would get:

 11:00 AM
 12:00 PM
 1:00 PM
 2:00 PM

I am trying to avoid having to store every specific hour a store might be open and just store the range (I need to compare the hours against other times)

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No loops, recursive CTEs or numbers table required.

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...