我想使用当前时间在开始时间至结束时间
之间选择班次ShiftID OrgID ShiftName StartTime EndTime
13 1-1 General 1900-01-01 09:00:00.000 1900-01-01 17:00:00.000
14 1-2 Morning 1900-01-01 08:00:00.000 1900-01-01 15:00:00.000
15 1-3 Evening 1900-01-01 15:00:00.000 1900-01-01 21:00:00.000
16 1-4 Night 1900-01-01 21:00:00.000 1900-01-01 08:00:00.000
答案 0 :(得分:1)
根据您的问题,您可以尝试使用CAST(CAST(GETDATE() AS TIME) AS DATETIME)
将日期设置为1900-01-01
,而我们只比较time
值。
检查Night
需要使用一些技巧,因为该值将跨越日期。
在GETDATE()
和'00:00:00'
之间的'08:00:00'
时间表示截止日期。
因此我们需要为CAST(CAST(GETDATE() AS TIME) AS DATETIME)
CREATE TABLE T(
ShiftID INT,
OrgID VARCHAR(50),
ShiftName VARCHAR(50),
StartTime DATETIME,
EndTime DATETIME
);
INSERT INTO T VALUES (13,'1-1','General','1900-01-01 09:00:00.000','1900-01-01 17:00:00.000');
INSERT INTO T VALUES (14,'1-2','Morning','1900-01-01 08:00:00.000','1900-01-01 15:00:00.000');
INSERT INTO T VALUES (15,'1-3','Evening','1900-01-01 15:00:00.000','1900-01-01 21:00:00.000');
INSERT INTO T VALUES (16,'1-4','Night','1900-01-01 21:00:00.000','1900-01-01 08:00:00.000');
查询1 :
SELECT t1.*
FROM T t1
WHERE
CASE WHEN CONVERT(datetime,CONVERT(varchar(8),GETDATE(),108)) BETWEEN CONVERT(DATETIME,'00:00:00') AND CONVERT(DATETIME,'00:08:00')
THEN CONVERT(datetime,CONVERT(varchar(8),GETDATE(),108)) + 1
ELSE CONVERT(datetime,CONVERT(varchar(8),GETDATE(),108))
END
BETWEEN StartTime
AND
CASE WHEN ShiftName = 'Night'
THEN EndTime + 1
ELSE EndTime
END
Results :
| ShiftID | OrgID | ShiftName | StartTime | EndTime |
|---------|-------|-----------|----------------------|----------------------|
| 13 | 1-1 | General | 1900-01-01T09:00:00Z | 1900-01-01T17:00:00Z |
| 14 | 1-2 | Morning | 1900-01-01T08:00:00Z | 1900-01-01T15:00:00Z |
答案 1 :(得分:1)
简单的BETWEEN
子句不足以处理午夜情况。您可以执行以下操作:
SELECT *
FROM shifts
CROSS APPLY (
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(8), GETDATE(), 108)) AS CurrTime
) AS ca
WHERE
(EndTime > StartTime AND CurrTime >= StartTime AND CurrTime < EndTime) OR
(EndTime < StartTime AND (CurrTime < EndTime OR CurrTime >= StartTime));
答案 2 :(得分:1)
假设StartTime和EndTime处于日期时间数据类型
declare @now datetime
-- this will convert current date time to 1900-01-01 + time
select @now = convert(datetime, convert(time, getdate()))
select *
from @shift s
where @now >= StartTime
and @now < case when StartTime < EndTime
then EndTime
else dateadd(day, 1, EndTime)
end