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 
相关问题