0

我想檢查我的當前日期時間是否在兩個日期時間之間。如何檢查來自Sql的有效日期時間表

我第一次2016-05-19 04:23:00.000和第二次2016-05-19 04:50:00.000

如何編寫一個查詢返回true,如果當前日期時間是第一和第二時間否則返回false之間?

+7

只有幾百個左右的例子,如果你谷歌它。這裏是一個解決方案的SO帖子... http://stackoverflow.com/questions/11745650/isdate-function-in-sql-evaluates-invalid-dates-as-valid – dinotom

回答

0
Select * 
From Table 
Where 
    ('2016-05-19 04:23:00.000' <= dateColumn) 
    And (dateColumn < '2016-05-19 04:50:00.000') 
+0

如果我有時間「2016- 05-19 04:23:00.000''存儲在表中?我將如何在這裏得到這個時間? –

+0

@JaniMani查看我的編輯和我對你接受的答案的評論。避免在'Date'之間使用'Between'。 – shadow

1

基本情況下的表達式可以很容易地做到這一點。

case when FirstTime <= getdate() AND getdate() <= SecondDate 
    then 'True' 
    else 'False' 
end 
0

停止,除非你是絕對相信,你知道你在做什麼,你ABSOLUTELY瞭解日期時間概念,日期時間之間使用。

create table #test(
    Id int not null identity(1,1) primary key clustered, 
    ActionDate datetime not null 
) 

insert into #test values 
('2015-12-31 23:59:59.99'), 
('2016-01-01'), 
('2016-01-10'), 
('2016-01-31 23:59:59.99'), 
('2016-02-01') 

select * from #test 
-- all the rows 
1 2015-12-31 23:59:59.990 
2 2016-01-01 00:00:00.000 
3 2016-01-10 00:00:00.000 
4 2016-01-31 23:59:59.990 
5 2016-02-01 00:00:00.000 


-- lets locate all of January 

-- using between 
select * from #test 
where 
    (ActionDate between '2016-01-01' and '2016-01-31') 

2 2016-01-01 00:00:00.000 
3 2016-01-10 00:00:00.000 
-- missing row 4 

select * from #test 
where 
    (ActionDate between '2016-01-01' and '2016-02-01') 

2 2016-01-01 00:00:00.000 
3 2016-01-10 00:00:00.000 
4 2016-01-31 23:59:59.990 
5 2016-02-01 00:00:00.000 -- this is not January 

-- using <and> 
select * from #test 
where 
    ('2016-01-01' <= ActionDate) 
    and (ActionDate < '2016-02-01') 

2 2016-01-01 00:00:00.000 
3 2016-01-10 00:00:00.000 
4 2016-01-31 23:59:59.990 


drop table #test 
相關問題