sql-server - 在 SQL Server 存储过程中查找当前时间之前最接近的值
问题描述
我的表中有 8 小时这样的班次Shift
,shiftstart
数据shiftend
类型为time(7)
.
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 小时基于上一次班次结束时班次开始的最接近值
解决方案
尝试这个:
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
推荐阅读
- kotlin - 微调器和切换按钮的中性状态
- python - 在 Anaconda 终端中找不到模块错误
- c - 如何在字符串中的每个单词后添加一个字符?
- r - 如何让 str_replace (和其他 stringr )函数忽略正则表达式(从字面上处理字符串)?
- javascript - 在 Nuxt JS 中导入 SVG 时,Jest 中出现“[Vue 警告]:无效的组件定义”
- phpstan - CakePHP3&PHPStan:如何在为 CakePHP3 应用程序运行 PHPStan 时删除“未定义的方法..”模型错误
- c - 为什么我的信号处理程序在这里没有被多次调用?
- r - 使用 paste 和 rep 函数指定序列的顺序
- c# - 成对交换链表
- kotlin - 如何设置 Kotlin/Native 项目,以便将资源与可执行文件放在一起?