所以我想要生成特定时间范围内的所有小时。
因此,考虑到上午 11 点到下午 2:00 的范围,我会得到:
11:00 AM
12:00 PM
1:00 PM
2:00 PM
我试图避免必须存储商店可能营业的每个特定时间,而只存储范围(我需要将时间与其他时间进行比较)
谢谢
无需循环、递归 CTE 或数字表。
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;
您可以使用递归 CTE。 这将生成 11 点到 14 点之间的时间:
;with Hours as
(
select 11 as hr
union all
select hr + 1
from Hours
where hr < 14
)
select *
from Hours
如果您有数字表(如果没有,请单击链接创建一个)...
create table test(
startTime time
, endTime time
)
insert into test
select '11:00', '14:00'
select
dateadd(hh, n.n, t.startTime) as times
from test t
inner join Numbers n
-- assuming your numbers start at 1 rather than 0
on n.n-1 <= datediff(hh, t.startTime, t.endTime)
如果这是专门的,您可以创建一个仅包含 24 个值的小时表。
create table HoursInADay(
[hours] time not null
, constraint PK_HoursInADay primary key ([hours])
)
-- insert
insert into HoursInADay select '1:00'
insert into HoursInADay select '2:00'
insert into HoursInADay select '3:00'
insert into HoursInADay select '4:00'
insert into HoursInADay select '5:00'
insert into HoursInADay select '6:00'
insert into HoursInADay select '7:00'
...
select
h.[hours]
from test t
inner join HoursInADay h
on h.[hours] between t.startTime and t.endTime
我能想到的最简单的方法是只有 1 个永久表,其中包含所有时间的列表;总共 24 个条目。
Create table dbo.Hours (Hourly_Time Time NOT NULL)
Insert into dbo.Hours ...
然后,给定时间 A 和 B:
select * from dbo.Hours where Hourly_Time<=A and Hourly_Time>=B
@Andomar 非常感谢,你帮助了我,在你的代码上面有我的添加。
*----------------------------
create view vw_hoursalot as
with Hours as
(
select DATEADD(
dd, 0, DATEDIFF(
dd, 0, DATEADD (
year , -5 , getDate()
)
)
) as dtHr
union all
select DATEADD (minute , 30 , dtHr )
from Hours
where dtHr < DATEADD(
dd, 0, DATEDIFF(
dd, 0, DATEADD (
year , +5 , getDate()
)
)
)
)
select * from Hours
----------------------------
select * from vw_hoursalot option (maxrecursion 0)
----------------------------*
GENERATE_SERIES
构建一系列值/日期,如下所示:
SELECT FORMAT(DATEADD(HOUR, value, CAST('11:00:00' AS DATETIME)), 'h:mm tt')
FROM GENERATE_SERIES(0, 3);
时间 |
---|
11:00 上午 |
12:00 下午 |
下午 1:00 |
下午2:00 |