基本上我想要做的就是在
之间调整范围已经得到了这个
where @param_value_from_hour between From_Hour and To_Hour
当@param_value_from_hour让我们说16:00时它会起作用,但如果我必须在19:00搜索@param_value_from_hour怎么办?
答案 0 :(得分:0)
将time
列转换为datetime
并进行比较
declare @param_value_from_hour varchar(20) = '19:00'
;with myTable as (
select *
from (
values
(1, '7:00:00', '18:00:00')
, (2, '18:00:00', '7:00:00')
) t(Shift, From_Hour, To_Hour)
)
select
*
from
myTable
where
cast('20180101 ' + @param_value_from_hour as datetime) between
cast('20180101 ' + From_Hour as datetime)
and cast('20180101 ' + To_Hour as datetime) + case when From_Hour < To_Hour then 1 else 0 end
答案 1 :(得分:0)
如果逻辑是这样,如果期间的结束早于期间的开始,则假定期间跨越午夜(如果不是,我们需要一些其他形式的约定或事情得到绝望的含糊不清):
where
(@param_value_from_hour between From_Hour and To_Hour) or
(To_Hour < From_Hour and
(@param_value_from_hour < To_Hour or
From_Hour < @param_value_from_hour)
)
应该大致得到你想要的东西(如果需要,调整<
{/ 1}}
答案 2 :(得分:0)
试试这个:
CREATE TABLE Data (
Shift INT,
FromHour TIME,
ToHour TIME
);
INSERT INTO Data (Shift, FromHour, ToHour) VALUES
(1, '07:00:00', '18:00:00'),
(2, '18:00:00', '07:00:00');
DECLARE @Param TIME= '16:00:00'; --Change that to '19:00:00'
SELECT *
FROM Data
WHERE CAST(@Param AS DATETIME) BETWEEN
CAST(FromHour AS DATETIME)
AND
(CASE
WHEN (@Param >= '18:00:00' AND ToHour = '07:00:00')
THEN DATEADD(D, 1, CAST(ToHour AS DATETIME))
ELSE CAST(ToHour AS DATETIME)
END)
答案 3 :(得分:0)
感谢您的所有宝贵回复
所以这是2个答案结合的答案
declare @param_value_from_hour varchar(20) = '19:00'
;with myTable as (
select *
from (
values
(1, '07:00:00', '15:00:00')
, (2, '15:00:00', '23:00:00')
, (3, '23:00:00', '07:00:00')
) t(Shift, From_Hour, To_Hour)
)
select
*
from
myTable
where
(@param_value_from_hour between From_Hour and To_Hour) or
(To_Hour < From_Hour and
(@param_value_from_hour < To_Hour or
From_Hour < @param_value_from_hour)
)
谢谢你们,你真棒!