2011-04-12 42 views
4

我在我的應用程序中有開始時間和結束時間。我現在需要檢查SQL查詢中這段時間之間是否有時間。如何檢查2個給定日期之間是否有數據範圍?

如何編寫查詢。

謝謝

+0

在關鍵字之間使用。 – 2011-04-12 12:52:53

+0

我已經使用過,只有 – 2011-04-12 13:02:47

回答

11

這應該適合你。

Select * From MyTable 
Where timecreated Between Cast('7/20/08 12:01:01' As DateTime) And Cast('7/20/09 12:01:01' as DateTime) 
+2

你不應該投日期嗎? – Mayo 2011-04-12 12:55:14

+0

如果我選擇的時間範圍是從03:00到05:00,並且如果添加了時間03-04:00,那麼它顯示的是正確的,但是如果我添加了01:00-03:00 PM,則也落在這個範圍之內。 – 2011-04-12 13:10:28

0

這也將工作: -

select * from tablename where time between '7/7/2009 12:35:35' and '7/7/2010 23:35:35' 
1

我會建議比較日期時間時,不使用between。結果往往不是你想要的。

返回TRUE之間。如果 與test_expression的值大於或 等於與begin_expression 的值且小於或等於 end_expression的值,。使用結果

之間
select * 
from @T 
where dt between '2011-04-12T10:00:00' and '2011-04-12T11:00:00' 

演示

declare @T table (dt datetime) 

insert into @T values('2011-04-12T09:00:00') 
insert into @T values('2011-04-12T10:00:00') 
insert into @T values('2011-04-12T11:00:00') 
insert into @T values('2011-04-12T12:00:00') 

查詢

測試數據:11:00被包含在結果中。

dt 
2011-04-12 10:00:00.000 
2011-04-12 11:00:00.000 

重寫使用>=<而不是查詢。

select * 
from @T 
where 
    dt >= '2011-04-12T10:00:00' and 
    dt < '2011-04-12T11:00:00' 

結果

dt 
2011-04-12 10:00:00.000 

問題提示中的要檢查是否有重疊的日期間隔標題。如果是這種情況,你可以看看這個問題How can I determine in SQL Server if a dateTime range overlaps another

相關問題