如何从 Sql Table 检查有效日期时间

How to Check Valid Date Time from Sql Table

我想检查我当前的日期时间是否在两个日期时间之间。

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

如果当前日期时间在第一次和第二次之间,如何将查询写入 return true,否则 return false?

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

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

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

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

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