根据时间选择行

时间:2012-07-02 13:42:24

标签: sql-server

我在使用之前选择了基于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类型列来引用。有没有办法在引用单独的时间和日期字段的特定时间范围之间获得一行?感谢

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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 <