簡體   English   中英

在這種情況下,帶有和的正確if語句在SQL Server中

[英]The correct if statement with and in this situation in 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)

我只想獲得此時間范圍內的班次convert(time(0),dateadd(HOUR,15,getdate()),108)

您可以像這樣使用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;

如果您使用@selectedTime的時間是在s.time_Out都經過午夜之前s.time_Out的時間,那么查詢中的CASE語句就會計算出來,這兩個時間都將被調整,從而可以選擇最后一個班次。

可能有一個更簡單的解決方案,但是可以使用您提供的數據。

對不起,我一個答案,但我不能發表評論相當,但...這是丹拿的答復意見。

您可以嘗試拆分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;
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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM