SQL 服务器时间与午夜时间的比较

SQL Server Time Comparison with Time over midnight

我在 SQL 服务器中有一个 table,它存储 Start_Time(时间 (7))和 End_Time(时间 (7))。

其中存储的值为

                  Start_Time        End_Time
                  15:00:00.0000000  01:00:00.0000000

我有一个查询应该return这一行:

                 Select * from Table Where MyTime >= Start_Time and MyTime < 
                  End_Time

对于 MyTime 值 = 16:00:00,这应该 return 一行。但是由于 End_Time 是在午夜之后,它不会 return 任何行。我不能使用日期 + 时间列,因为我将此 Start_Time 和 End_Time table 用作通用 table,我将其与另一个 table 结合以获取我的数据.

有人可以在不改变列类型的情况下提出解决方法吗?

谢谢。

您可以比较开始和结束时间,然后在比较逻辑中使用:

Select t.*
from Table t
Where (Start_time <= End_time and MyTime >= Start_Time and MyTime <  End_Time) or
      (Start_time > End_time and MyTime < Start_Time and MyTime >=  End_Time);

您需要在 WHERE 子句中包含此选项:

Select *
from Table
Where (Start_Time > End_time AND myTime >= start_time) -- Answer your case
   OR MyTime between start_time and end_time -- All the rest