检查新的开始时间和结束时间是否与同一日期的现有开始时间和结束时间不冲突

时间:2017-08-01 07:44:52

标签: sql sql-server sql-server-2008

我有一个包含这些列的Schedule表:

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

1 个答案:

答案 0 :(得分: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.

当然,如果您要先将表格中的类型更改为日期&amp;那时候可以避免演员阵容。