2017-08-01 80 views
0

我有这些列计划表冲突:检查是否有新的开始时间和结束时间不与现有的开始时间和结束时间在同一天

LeaveDate DateTime 
Start_Time varchar 
End_Time varchar 

之前,我添加值,我需要一个该查询将首先检查我的Start_Time,End_Time和LeaveDate输入是否与现有记录不冲突。

这里是我现有的记录:

Rec LeaveDate Start_Time End_Time 
1 01/01/2017 9:00:00  13:30:00 

有效输入 - 请注意,新START_TIME可以等于在同一日期的现有END_TIME:

LeaveDate Start_Time End_Time 
01/01/2017 13:30:00  18:00:00 

或者

LeaveDate Start_Time End_Time 
01/01/2017 13:43:00  18:00:00 

无效输入:

LeaveDate Start_Time End_Time 
01/01/2017 13:29:00  18:00:00 

或者

LeaveDate Start_Time End_Time 
01/01/2017 10:00:00  11:00:00 
+6

您应该做的第一件事是更改您的表的数据类型。 'LeaveDate'应该是'Date'类型,'Start_Time'和'End_Time'应该是'Time'类型。欲了解更多信息,请阅读Aaron Bertrand [踢坏的坏习惯:选择错误的数据类型](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/12/bad-habits-to-kick-using- the-wrong-data-type.aspx)接下来要做的是阅读['overlap' tag wiki。](https://stackoverflow.com/tags/overlap/info) –

+1

另外,可以安排一些东西在午夜之前开始,在午夜之后结束?如果是这样,那会让事情变得复杂。 –

+0

这是在SQL Server中,没有仅限日期和时间的数据类型。只有日期时间。关于午夜之前/之后,现在我不会包含该功能 –

回答

0

您可以先检查新的时间表不会与现有的记录重叠。如果没有,则插入并在出现错误时提出错误。

例如:

-- using a table variable for demonstration purposes 
declare @Schedule table (Id int identity(1,1) primary key, LeaveDate datetime, Start_Time varchar(8), End_Time varchar(8)); 

insert into @Schedule (LeaveDate, Start_Time, End_Time) values 
('2017-01-01','09:00:00','13:30:00'); 

declare @LeaveDate date = '2017-01-01'; 
declare @StartTime time = '13:28:00'; 
declare @EndTime time = '14:00:00'; 

if not exists(
    select 1 from @Schedule 
    where LeaveDate = convert(datetime,@LeaveDate,20) 
     and ((@StartTime > cast(Start_Time as time) and @StartTime < cast(End_Time as time)) or 
      (@EndTime > cast(Start_Time as time) and @EndTime < cast(End_Time as time)) 
     ) 
) 
begin 
    insert into @Schedule (LeaveDate, Start_Time, End_Time) values (@LeaveDate,cast(@StartTime as varchar(8)),cast(@EndTime as varchar(8))); 
end 
else 
begin 
    declare @ErrorMessage varchar(max) = concat('schedule [',convert(varchar,@LeaveDate,20),',',cast(@StartTime as varchar(8)),',',cast(@EndTime as varchar(8)),'] overlaps.'); 
    RAISERROR(@ErrorMessage,16,16); 
end; 

对于在例如它会引发错误

schedule [2017-01-01,13:28:00,14:00:00] overlaps. 

当然,如果你想先更改类型在表中日期&时间值那么可以避免演员阵容。

相关问题