0

我想检查我当前的 DateTime 是否在两个 DateTimes 之间。

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

如果当前 DateTime 介于第一次和第二次之间,如何编写查询以返回 true,否则返回 false?

4

3 回答 3

1

一个基本的 case 表达式可以很容易地做到这一点。

case when FirstTime <= getdate() AND getdate() <= SecondDate 
    then 'True' 
    else 'False' 
end
于 2016-05-20T18:26:47.753 回答
0

除非您绝对确定自己知道自己在做什么并且您绝对理解日期时间的概念,否则请停止在日期时间之间使用。

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 
于 2016-05-21T05:40:57.120 回答
0
Select *
From Table
Where
  ( '2016-05-19 04:23:00.000' <= dateColumn )
  And ( dateColumn < '2016-05-19 04:50:00.000' )
于 2016-05-20T18:02:28.890 回答