Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 两次之间的sql时间_Sql Server - Fatal编程技术网

Sql server 两次之间的sql时间

Sql server 两次之间的sql时间,sql-server,Sql Server,我有一个表EmployeeShift,在其中插入员工轮班。 在插入/更新记录之前,我想知道用户是否有任何移位(对于给定的datime范围) 我试过下面的代码,但它不工作 declare @Datefrom date declare @Dateto date declare @Timefrom nvarchar(200) declare @Timeto nvarchar(200) set @Datefrom ='2017-01-12' set @Dateto ='2017-01-

我有一个表EmployeeShift,在其中插入员工轮班。 在插入/更新记录之前,我想知道用户是否有任何移位(对于给定的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

我是否需要连接日期和时间以获得日期时间字段

您的表存在设计问题,导致您做的工作超出了需要。如果在单独的列中有日期和时间值,则总是需要做额外的工作来执行这样的查询。您应该将轮班开始时间和结束时间存储为
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;

标记您正在使用的dbms。该代码是特定于产品的。好的,谢谢@jarlh.。什么不起作用?您已经将两次
TimeTo
设置为
并忘记了
TimeFrom
如果要存储日期和时间,为什么不使用专为保存此类值而设计的类型-
datetime2
?通过拆分数据并将其中一些数据存储在错误的数据类型中,您正在为自己制造问题。