使用SQL查找日期时间是否在特定时间间隔内

时间:2010-09-02 08:05:34

标签: sql sql-server tsql

如何在SQL select语句中查明表中的datetime列是否在特定小时间隔(例如13:07 - 15:15)和特定日期(例如星期四)?

谢谢,

4 个答案:

答案 0 :(得分:1)

select * From #t

Where DatePart(hour, [date]) >=10 
and DatePart(hour, [date]) <= 11

And DatePart(minute, [date]) >= 15
And DatePart(minute, [date]) <= 45

and Datename(dw,[date]) = 'Thursday' 

答案 1 :(得分:1)

星期几和开始/结束时间作为参数

declare @tbl table ( datecol datetime )

declare @startHour int
declare @endHour int
declare @specificDay varchar(10)

set @startHour = 13
set @endHour = 15
set @specificDay = 'Thursday'

insert into @tbl select getdate()
insert into @tbl select dateadd(hh, 1, getdate())
insert into @tbl select dateadd(n, 10, getdate())
insert into @tbl select dateadd(dd, 2, getdate())

select * from @tbl 
where  DATENAME(dw, datecol) = @specificDay
and datepart(hh, datecol) >= 13 
and datepart(hh, datecol) <= 15

修改

declare @tbl table ( datecol datetime )

declare @startHour varchar(10)
declare @endHour varchar(10)
declare @specificDay varchar(10)

set @startHour = '13:05:00'
set @endHour = '15:30:00'
set @specificDay = 'Thursday'

insert into @tbl select getdate()
insert into @tbl select dateadd(hh, 1, getdate())
insert into @tbl select dateadd(n, 10, getdate())
insert into @tbl select dateadd(dd, 2, getdate())

select * from @tbl 
where  DATENAME(dw, datecol) = @specificDay
and CONVERT(VARCHAR(8), datecol,8) >= @startHour
and CONVERT(VARCHAR(8), datecol,8) <= @endHour

如果时间有几小时和几分钟的部分只有像'13:05'那么就像这样改变

and CONVERT(VARCHAR(5), datecol,8) >= @startHour
and CONVERT(VARCHAR(5), datecol,8) <= @endHour

答案 2 :(得分:0)

您可以使用BETWEEN关键字。例如... WHERE MyDate BETWEEN Date1 and Date2

答案 3 :(得分:0)

我通常使用以下语法:

DECLARE @FromTime DATETIME
DECLARE @ToTime DATETIME
SET @FromTime = '2010-09-02T13:00:00'
SET @ToTime = '2010-09-02T15:00:00'

SELECT Something
FROM MyTable
WHERE DateField >= @FromTime
    AND DateField < @ToTime

您可以使用BETWEEN,但我通常更喜欢以上,而BETWEEN是包含,例如在此示例中,使用BETWEEN将包括时间为15:00:00.000

的记录