【问题标题】:Checking is time in specific time range检查是特定时间范围内的时间
【发布时间】:2020-07-28 03:47:58
【问题描述】:

我想在time 格式上使用CASE Statement 做出决定。但是无法使用time 格式做出正确的决定,因为我的时间范围的结束时间小于开始时间。让我用代码解释一下;

DECLARE @Startdate datetime
DECLARE @START_TIME time(0)
DECLARE @END_TIME time(0)

SET @Startdate='2020-04-15 16:00:00.000'
SET @START_TIME='15:30:00'
SET @END_TIME='01:29:59'

select 
CASE WHEN CAST(@Startdate as time(0)) between @START_TIME and @END_TIME  THEN 1 ELSE 0 END

我在 DB 中也有如下表;

ID  START_TIME  END_TIME
1   05:30:00    15:29:59
2   15:30:00    01:29:59

只是我想检查即将到来的datetime 值与ID 完全匹配的时间。我不在乎日期部分。我怎样才能做到这一点?

提前谢谢你。

【问题讨论】:

  • 您的 SQL 数据库是什么(例如 MySQL、SQL Server、Oracle 等)?
  • Microsoft SQL Server

标签: sql sql-server tsql date time


【解决方案1】:

一种方法是:

select case 
    when 
        (
            @end_time >= @start_time 
            and cast(@startdate as time(0)) >= @start_time 
            and cast(@startdate as time(0)) <= @end_time  
        )
        or (
            @end_time < @start_time 
            and (
                   cast(@startdate as time(0)) >= @start_time 
                or cast(@startdate as time(0)) <= @end_time
            )
        )           
    then 1 
    else 0 
end

【讨论】:

  • @Startdate='2020-04-15 13:00:00.000'@Startdate='2020-04-15 16:00:00.000' 都返回 1。但 13:00:00 应该返回 0。
  • @Lacrymae:啊,是的,没错。我稍微修改了查询,现在似乎产生了正确的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-23
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
相关资源
最近更新 更多