如何用SQL Server知道两次之间是否有一个小时

时间:2015-01-20 15:05:05

标签: sql sql-server database

我有这个:

DECLARE @HourBegin time = '18:00'
DECLARE @HourEnd time = '02:00'
DECLARE @Hour TIME = '20:00'

BEGIN TRAN 
    IF(@Hour between @HourBegin and @HourEnd)
    BEGIN   
        SELECT  
            CONVERT(BIT, 1) AS ERROR, 
            '1'  AS MSG     
    END
    ELSE
    BEGIN   
        SELECT  
            CONVERT(BIT,1) AS ERROR, 
            '0'  AS MSG     
    END
COMMIT TRAN 

问题是变量@HourEnd是第二天,BETWEEN总是给我变量@Hour不在指定范围内

!HELP!

2 个答案:

答案 0 :(得分:2)

你可以这样做。如果你得到endDate < StartDate,你可能应该在endDate中加1天。所以你最终得到:

DECLARE @HourBegin time = '18:00'
DECLARE @HourEnd time = '02:00'
DECLARE @Hour TIME = '19:00'

DECLARE @DateBegin DATETIME
DECLARE @DateEnd DATETIME
DECLARE @Date DATETIME

select @DateBegin = CAST(@HourBegin AS DATETIME)
select @DateEnd = CAST(@HourEnd AS DATETIME)
select @Date = CAST(@Hour AS DATETIME)

IF(@DateEnd < @DateBegin)
    SET @DateEnd = DATEADD(dd, 1, @DateEnd)

BEGIN TRAN 
    IF(@Date between @DateBegin and @DateEnd)
    BEGIN   
            SELECT  CONVERT(BIT,1) AS ERROR, '1'  AS MSG     
    END
    ELSE
    BEGIN   
            SELECT  CONVERT(BIT,1) AS ERROR, '0'  AS MSG     
    END
COMMIT TRAN 

答案 1 :(得分:1)

这是一个处理这个问题的函数:

CREATE function dbo.f_between
(
  @HourBegin DATETIME,
  @HourEnd DATETIME,
  @Hour DATETIME
)RETURNS bit
as
BEGIN
RETURN CASE WHEN
    @Hour between @HourBegin and @HourEnd or
   ((@Hour <= @HourEnd or @hour >= @HourBegin) and @HourBegin > @HourEnd) 
   THEN cast(1 as bit) 
ELSE cast(0 as bit) END
END

以下是如何使用它的示例:

测试数据和表格:

DECLARE @t table(HourBegin time, HourEnd time, hour time)
insert @t values('06:00', '12:00', '01:00') -- not between
insert @t values('06:00', '12:00', '09:00') -- between
insert @t values('06:00', '12:00', '15:00') -- not between
insert @t values('12:00', '06:00', '01:00') -- between
insert @t values('12:00', '06:00', '09:00') -- not between
insert @t values('12:00', '06:00', '15:00') -- between

查询:

SELECT 
  HourBegin, 
  HourEnd, 
  hour, 
  dbo.f_between(HourBegin, HourEnd, hour) betweenbit
FROM @t

结果:

HourBegin  HourEnd   hour      betweenbit
06:00:00   12:00:00  01:00:00  0
06:00:00   12:00:00  09:00:00  1
06:00:00   12:00:00  15:00:00  0
12:00:00   06:00:00  01:00:00  1
12:00:00   06:00:00  09:00:00  0
12:00:00   06:00:00  15:00:00  1