我有一个表EmployeeShifts,我在那里插入员工班次。 在插入/更新记录之前,我想知道用户是否有任何移位(对于给定的datime范围)。
我尝试了下面的代码,但它不起作用。
declare @Datefrom date
declare @Dateto date
declare @Timefrom nvarchar(200)
declare @Timeto nvarchar(200)
set @Datefrom ='2017-01-12'
set @Dateto ='2017-01-30'
set @Timefrom='03:00 pm'
set @Timeto='11:30 pm'
if exists(select CAST(timefrom as time), CAST(timeto as time),* from EmployeeShifts where [Uid]=11 and Active=1 and
((Datefrom between @Datefrom and @Dateto and
((CAST(timefrom As Time) between CAST(@Timefrom As Time) and CAST(@Timeto As Time)) or (CAST(timeto As Time) between CAST(@Timefrom As Time) and CAST(@Timeto As Time))))
or
(Dateto between @Datefrom and @Dateto and
((CAST(timefrom As Time) between CAST(@Timefrom As Time) and CAST(@Timeto As Time)) or (CAST(timeto As Time) between CAST(@Timefrom As Time) and CAST(@Timeto As Time)))
)))
begin
print 'User is already in a shift.'
end
我是否需要连接日期和时间来获取日期时间字段?
答案 0 :(得分:0)
您的表存在设计问题,导致您执行的工作超出了您的需要。如果在单独的列中有日期和时间值,则总是需要执行额外的工作来执行这样的查询。您应将班次开始时间和结束时间存储为datetime
值。看看这个样本,看看你能让你的生活变得多么简单:
CREATE TABLE #EmployeeShifts
(
EmployeeId INT ,
StartTime DATETIME ,
EndTime DATETIME
);
INSERT INTO #EmployeeShifts
( EmployeeId, StartTime, EndTime )
VALUES ( 1, '20170105 09:00:00', '20170105 17:00:00' ),
( 1, '20170106 09:00:00', '20170106 17:00:00' ),
( 1, '20170107 09:00:00', '20170107 17:00:00' ),
( 2, '20170105 09:00:00', '20170105 17:00:00' ),
( 2, '20170108 09:00:00', '20170108 17:00:00' ),
( 2, '20170109 09:00:00', '20170109 17:00:00' );
DECLARE @from DATETIME = '20170106 07:00:00' ,
@to DATETIME = '20170108 18:00:00';
SELECT *
FROM #EmployeeShifts
WHERE StartTime BETWEEN @from AND @to
AND EndTime BETWEEN @from AND @to;
DROP TABLE #EmployeeShifts;