Sql 我获取的数据介于开始时间和结束时间之间,但如果结束时间为空会怎么样?

Sql 我获取的数据介于开始时间和结束时间之间,但如果结束时间为空会怎么样?,sql,sql-server,tsql,date,Sql,Sql Server,Tsql,Date,我有一个停车场数据库。我编写了一个存储过程来获取给定特定日期时间的所有空点。我的质询如下: select Count(ParkingSlotId) as 'Empty Spots' from [ParkingLot].[ParkingSlot] where ParkingSlotId not in (select ParkingSlotId from [Transaction].[ParkingTransaction] where

我有一个停车场数据库。我编写了一个存储过程来获取给定特定日期时间的所有空点。我的质询如下:

 select Count(ParkingSlotId) as 'Empty Spots'
   from [ParkingLot].[ParkingSlot]
  where ParkingSlotId not in
       (select ParkingSlotId
          from [Transaction].[ParkingTransaction]
         where @searchTime between TimeIn and [TimeOut]) 

除非TimeOut为null(表示此人尚未离开),否则此查询工作正常。如果TimeOut为null,如何获取此数据?

TiemOut
为null时,子查询中的条件变为:

where  @searchTime between TimeIn and null
这将始终计算为false(不小于
null

解决方案是显式处理该用例:

select Count(ParkingSlotId) as 'Empty Spots' 
from [ParkingLot].[ParkingSlot] 
where ParkingSlotId not in (
    select ParkingSlotId 
    from [Transaction].[ParkingTransaction] 
    where 
        @searchTime >= TimeIn
        and ([TimeOut] is null or @searchTime <= [TimeOut])
)
选择计数(驻车液)作为“空位”
来自[停车场][停车场]
哪里没有停车场(
选择ParkingSlotId
来自【交易】【ParkingTransaction】
哪里
@searchTime>=TimeIn

并且([TimeOut]为null或@searchTime当
TiemOut
为null时,子查询中的条件变为:

where  @searchTime between TimeIn and null
这将始终计算为false(不小于
null

解决方案是显式处理该用例:

select Count(ParkingSlotId) as 'Empty Spots' 
from [ParkingLot].[ParkingSlot] 
where ParkingSlotId not in (
    select ParkingSlotId 
    from [Transaction].[ParkingTransaction] 
    where 
        @searchTime >= TimeIn
        and ([TimeOut] is null or @searchTime <= [TimeOut])
)
选择计数(驻车液)作为“空位”
来自[停车场][停车场]
哪里没有停车场(
选择ParkingSlotId
来自【交易】【ParkingTransaction】
哪里
@searchTime>=TimeIn

和([TimeOut]为null或@searchTime线索:您需要一个or子句来涵盖该场景(即searchTime在输入时间之后,输出时间为null的场景),如果假设为,如果TimeOut为null,则返回记录,并且不关心使用过于疯狂的未来日期。您可以始终执行ISNULL(超时,'2099-01-01')。否则,GMB提供的答案是最好的路线。我的建议更像是一个愚蠢的想法,你可以使用。提示:你需要一个OR子句来涵盖该场景(即搜索时间在in time之后,out time为null的场景)如果假设是,如果TimeOut为null,则返回记录,并且不关心使用过于疯狂的未来日期。您可以始终执行ISNULL(TimeOut,'2099-01-01')。否则,GMB提供的答案是最佳路线。我的建议更像是一个愚蠢的想法,您可以使用。