0

I have a requirement where I need to assign some resource for some tine frame .For example

Existing in Database : John Smith -- 3/1/2011 -- 6:00 AM To 7:00 AM -- Economics
To Be Inserted: John Smith -- 3/1/2011 -- 6:30 AM to 7:00 AM -- Maths

Here while inserting second row I want to check this time overlap if its overlapping I want to skip insert.How can I achieve this ?I have Date , FromTime and ToTime in seperate columns.

Pit Digger
  • 9,618
  • 23
  • 78
  • 122
  • Same Question: http://stackoverflow.com/questions/781895/checking-for-time-range-overlap-the-watchman-problem-sql – Four Feb 28 '11 at 14:35

4 Answers4

2

use computed dates using a conversion:

cast(cast(mydatecolumn as varchar(20)) + ' ' + 
 cast(mytimecolumn as varchar(20)) as datetime)

yields e.g. start_datetime and end_datetime

assume variables: @inserted_start_datetime, @inserted_end_datetime, @name

Insert Into MyTable(<values>)
Where not exists ( 
 select * from table t2 
 where name = @name 
 and (@inserted_start_datetime between start_datetime and end_datetime 
  or @inserted_end_datetime between start_datetime and end_datetime 
  or start_datetime between @inserted_start_datetime and @inserted_end_datetime 
  or end_datetime between @inserted_start_datetime and @inserted_end_datetime ))

EDITED

jenson-button-event
  • 18,101
  • 11
  • 89
  • 155
0

if your from to dates are timedates in the database you could try something like this

if not exists ( select * from table where name = @name and @startTime between startTime and endTime or @endTime between startTime and endTime ) begin

do insert.

where @name = John Smith @startTime = 3/1/2011 6:30 @endTime = 3/1/2011 7:00

end

shaine
  • 549
  • 5
  • 12
0

Basically like this:

INSERT INTO atable (Name, Date, FromTime, ToTime, Subject)
SELECT
  @Name,
  @Date,
  @FromTime,
  @ToTime,
  @Subject
WHERE NOT EXISTS (
  SELECT * FROM atable
  WHERE Name = @Name AND Date = @Date
    AND (FromTime >= @FromTime AND FromTime < @ToTime  OR
         @FromTime >= FromTime AND @FromTime < ToTime)
)

You might want to add some data conversion if and where needed.

Andriy M
  • 76,112
  • 17
  • 94
  • 154
0

Considering you have a table with two datetime columns start_time and end_time, the following query is going to return the conflicting rows. If no results are returned it means there is no conflicts.

SELECT * FROM your_table
WHERE start_time < [intended_end_time] AND end_time > [intended_start_time];
Claudson Martins
  • 348
  • 1
  • 3
  • 14