1

在使用之前,我已经根据 DateTime 选择了行:

DATEADD(day, -1, GetDate()) AND GETDATE()

获取自昨天以来的最新记录,以及

 DECLARE @today DATETIME = CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)  
DATEADD(mi, 00, DATEADD(hh, 8, @today)) AND DATEADD(hh, 9, @today)

为了获得从当天开始的某个时间范围之间的行。现在我有一个表,它有一个单独的时间和日期列,所以这两个都不起作用。当我尝试上述任何一种方法时,我总是会收到错误消息:“数据类型时间和日期时间在大于或等于运算符中不兼容。” 我知道问题是我没有要引用的 DateTime 类型列。有没有办法在引用单独的时间和日期字段的某个时间范围之间获得一行?谢谢

4

2 回答 2

2

您可以将日期和时间字段一起添加以创建一个日期/时间字段以进行比较:

create table #temp (id int, d date, t time)
insert into #temp values (1, '1/1/2000', '1:00 PM')
insert into #temp values (2, '1/1/2000', '2:00 PM')
insert into #temp values (3, '1/1/2000', '3:00 PM')

select * from #temp where cast(d as datetime) + cast(t as datetime) between '1/1/2000 1:10 PM' and '1/1/2000 2:30 PM'

因此,如果您DATEADD()的设置正确,您可以这样做:

SELECT * FROM sometable WHERE cast(DateField as datetime) + cast(TimeField as datetime) BETWEEN DATEADD(mi, 00, DATEADD(hh, 8, @today)) AND DATEADD(hh, 9, @today)
于 2012-07-02T13:48:15.510 回答
1
DECLARE @today DATE = SYSDATETIME();
DECLARE @start DATETIME = DATEADD(HOUR, 8, @today);
DECLARE @end   DATETIME = DATEADD(HOUR, 1, @start);

SELECT ... FROM dbo.table ...
WHERE date_column = @today -- to narrow search first, efficiently, if indexed
AND DATEADD(DAY, DATEDIFF(DAY, 0, date_column), CONVERT(DATETIME, time_column)) >= @start
AND DATEADD(DAY, DATEDIFF(DAY, 0, date_column), CONVERT(DATETIME, time_column)) <  @end;
---- you may want <= here rather than <
于 2012-07-02T13:55:35.137 回答