您应该使用行生成器。我使用 Itzik Ben Gan 的行生成器:
create table #TableVar ( interval Time not null)
declare @elapsed int
declare @from_time time,
@to_time time
select @elapsed = 30,
@from_time = '08:00:00',
@to_time = '20:00:00'
;WITH
Nbrs_3( n ) AS ( SELECT 1 UNION SELECT 0 ),
Nbrs_2( n ) AS ( SELECT 1 FROM Nbrs_3 n1 CROSS JOIN Nbrs_3 n2 ),
Nbrs_1( n ) AS ( SELECT 1 FROM Nbrs_2 n1 CROSS JOIN Nbrs_2 n2 ),
Nbrs_0( n ) AS ( SELECT 1 FROM Nbrs_1 n1 CROSS JOIN Nbrs_1 n2 ),
Nbrs ( n ) AS ( SELECT 1 FROM Nbrs_0 n1 CROSS JOIN Nbrs_0 n2 ),
D ( n ) as (SELECT ROW_NUMBER() OVER (ORDER BY n) FROM Nbrs ),
all_times as (
SELECT
dateadd( minute, ( n - 1) * @elapsed, @from_time) as [a_time]
FROM
D
where
n <= ( 12 * 60.0 / @elapsed ) + 1
)
insert
into #TableVar
select * from all_times
结果:
;select * from #TableVar
interval
--------
08:00:00
08:30:00
09:00:00
09:30:00
...
19:00:00
19:30:00
20:00:00
* 已编辑 *由于 OP 更改要求:
您可以将日期时间转换为时间以获取时间部分:
create table #dates ( some_date dateTime not null)
insert into #dates values
( '2012-01-01 07:30:00' ),
( '2012-01-01 08:00:00' ),
( '2012-01-01 08:30:00' ),
( '2012-01-01 09:00:00' );
select d.*, t.*
from #dates d
left outer join #TableVar t
on cast( d.some_date as time ) = t.interval;
结果:
some_date interval
------------- --------
2012-01-01 07:30:000 _NULL_
2012-01-01 08:00:000 8:00:00
2012-01-01 08:30:000 8:30:00
2012-01-01 09:00:000 9:00:00