在SQL Server存储过程中查找当前时间之前的最接近值

时间:2019-04-26 04:57:13

标签: sql-server stored-procedures

我的表Shiftshiftstartshiftend数据类型为time(7)时,我有8个小时的班次。

ShiftNo ShiftName  ShiftStart  ShiftEnd  IsNextDay  IsBothNextDay
--------------------------------------------------------------------
   1    Shift1     7:00:00     14:59:59   0          0
   2    SHift2     15:00:00    22:59:59   0          0
   3    Shift3     23:00:00    7:00:00    1          0

如果我在07:10执行该过程,我应该获得shift3行

23:00:00.0000000-07:00:00.0000000 as timestamp 

我现有的程序是

declare @shift table
(
    shiftno     int,
    shiftstart  time(7),
    shiftend    time(7)
)

--  sample data
insert into @shift 
values (1, '07:00', '14:59:59'),
       (2, '15:00', '22:59:59'),
       (3, '23:00', '07:00:00')

DECLARE @Currenttime AS TIME

SET @Currentdate = GETDATE()  
SET @Currenttime = (SELECT CAST(@Currentdate AS TIME))
SET @PreviousShifttime = (SELECT DATEADD(HOUR, -8, @Currenttime))

--  the query
; with shifts as
(
    select  *, 
        shift_start = convert(datetime, shiftstart),
        shift_end   = case  when shiftstart < shiftend
                    then convert(datetime, shiftend)
                    else dateadd(day, 1, convert(datetime, shiftend))
                    end
    from    @shift
)
select *
from shifts
where convert(datetime, @PreviousShifttime) between shift_start and shift_end
   or dateadd(day, 1, convert(datetime, @PreviousShifttime)) between shift_start and shift_end

此过程正确返回当前移位行。但是我想根据上一个班次结束时的班次开始值的最接近值,不对前一个班次行进行硬编码-8小时

1 个答案:

答案 0 :(得分:0)

尝试一下:

declare @shift table(
    shiftno     int,
    shiftstart  time(7),
    shiftend    time(7)
)

insert into @shift values
(1, '07:00', '14:59:59'),
(2, '15:00', '22:59:59'),
(3, '23:00', '06:59:59') -- I changed shiftend here

SELECT p.*
FROM @shift c
JOIN @shift p ON c.shiftstart=DATEADD(SECOND,1,p.shiftend)
WHERE CAST(GETDATE() AS time) BETWEEN c.shiftstart AND c.shiftend

第二种形式:

declare @shift table(
    shiftno     int,
    shiftstart  time(7),
    shiftend    time(7)
)

insert into @shift values -- I changed all the shiftend here
(1, '07:00', '15:00'),
(2, '15:00', '23:00'),
(3, '23:00', '07:00')

DECLARE @CurTime time=CAST(GETDATE() AS time)

SELECT p.*
FROM @shift c
JOIN @shift p ON c.shiftstart=p.shiftend
WHERE @CurTime>=c.shiftstart
  AND @CurTime<c.shiftend