正确的if语句,并在这种情况下,在SQL Server

问题描述:

我在我的数据库得到这个数据正确的if语句,并在这种情况下,在SQL Server

id  shift_no time_in time_out 
--------------------------------------- 
1  Shift 1  06:00:00 14:00:00 
2  Shift 2  14:00:00 22:00:00 
3  Shift 3  22:00:00 06:00:00 

所以我得到了这个日期:

convert(time(0),dateadd(HOUR, 15, getdate()), 108) 

我想只得到转变,是这个时间转换的范围内(时间(0),DATEADD(HOUR,15,GETDATE()),108)

对不起,我不能评论还有尚未...这是Tanner回答的评论。

你可以尝试分裂3班次项:

INSERT INTO #shifts 
(
    shiftNo, 
    time_In, 
    time_Out 
) 
VALUES 
(1, '06:00:00', '14:00:00'), 
(2, '14:00:00', '22:00:00'), 
(3, '22:00:00', '23:59:59'), 
(3, '00:00:00', '06:00:00'); 

-- the selected time 
SELECT CONVERT(TIME(0), DATEADD(HOUR, 15, GETDATE()), 108); 

-- filter your shifts 
SELECT * 
FROM #shifts AS s 
WHERE CONVERT(TIME(0), DATEADD(HOUR, -6, GETDATE()), 108) 
BETWEEN s.time_In AND s.time_Out; 

DROP TABLE #shifts; 
+0

我可以尝试这件事情,这将是好的!谢谢:) – GGw

+0

这可能会工作,但取决于高度紧密,你的源数据必然会出现这些变化,看起来像是你可以解决的问题的解决方法。我稍后再试 – Tanner

select 

* 

from yourtable 

where 
time_in between getdate() and convert(time(0),dateadd(HOUR, 15, getdate()), 108) 
or time_out between getdate() and convert(time(0),dateadd(HOUR, 15, getdate()), 108) 
+0

注意,您的时间返回值6时52分55秒。所以不确定'这次的范围'是什么意思,所以我已经猜到你是指现在和之后的时间。 – Cloud

+0

我们不能使用getdate(),因为它返回datetime,而我得到的时间是时间(0) – GGw

可以使用BETWEEN与您的进出时间,像这样(注意下面的重新运行的):在查询工作了

CREATE TABLE #shifts 
(
    shiftNo INT, 
    time_In TIME(0), 
    time_Out TIME(0) 
); 

INSERT INTO #shifts 
(
    shiftNo, 
    time_In, 
    time_Out 
) 
VALUES 
(1, '06:00:00', '14:00:00'), 
(2, '14:00:00', '22:00:00'), 
(3, '22:00:00', '06:00:00'); 

-- the selected time 
DECLARE @selectedTime TIME(0) = CONVERT(TIME(0), DATEADD(HOUR, 12, GETDATE()), 108); 

-- modify the selected time if it falls in the shift that crosses midnight 
SET @selectedTime = CASE WHEN @selectedTime > '22:00:00' OR @selectedTime < '06:00:00' 
         THEN '22:01:00' -- modified value 
         ELSE @selectedTime -- regular value 
        END; 
-- show the time we are working with 
SELECT @selectedTime; 

-- filter your shifts 
SELECT * 
FROM #shifts AS s 
WHERE @selectedTime 
BETWEEN s.time_In AND CASE WHEN s.time_Out = '06:00:00' -- is the out time 6.00 
          THEN '23:59:59' -- change it to before midnight if so 
          ELSE s.time_Out -- keep the time as it is 
         END; 

DROP TABLE #shifts; 

CASE语句,如果你是@selectedTime工作时间是将s.time_Out之前跨越午夜时间它们都被调整,这允许选择最后一班。

有可能是一个更简单的解决方案,但这与您提供的数据一起工作。

+0

我不知道为什么先生,但它不返回任何值:我现在的时间是:22:58:37所以它应该在里面Shift 3但它不返回任何值 – GGw

+0

它为我做的... – PawelCz

+0

它虽然没有为我:( – GGw