Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
There are two columns FromMinutes and ToMinutes) in my table and i entered data like 5-15 , 16-30, 31-60
Now i want to prevent clashing of range when i enter new range. E.g. new range cant be between or overlap existing range like 7-10 is invalid.12-25 is invalid and 1-70 is invalid. How to write this query in insert procedure?

my table structure is :

CREATE TABLE HRM.tbAttendanceTimeSlots
(
SlotId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
FromMinutes INT NULL,
ToMinutes INT NULL
)

What I have tried:

i tried
IF EXISTS(SELECT 1 FROM HRM.tbAttendanceTimeSlots WHERE (@FromMinutes BETWEEN FromMinutes AND Tominutes) AND (@ToMinutes BETWEEN FromMinutes AND Tominutes))
BEGIN
RETURN -1 --clashing
END
ELSE
BEGIN
INSERT INTO HRM.tbAttendanceTimeSlots
(
FromMinutes, ToMinutes
)
VALUES
(
@FromMinutes,@ToMinutes
)
RETURN 1
END
Posted
Updated 13-Oct-17 3:04am
v3

I think that you only have to change AND with OR in your stament:

IF EXISTS(SELECT 1 FROM HRM.tbAttendanceTimeSlots WHERE (@FromMinutes BETWEEN FromMinutes AND Tominutes) OR  (@ToMinutes BETWEEN FromMinutes AND Tominutes))
BEGIN
RETURN -1 --clashing
END
ELSE
BEGIN
INSERT INTO HRM.tbAttendanceTimeSlots
(
FromMinutes, ToMinutes
)
VALUES
(
@FromMinutes,@ToMinutes
)
RETURN 1
END 
 
Share this answer
 
Comments
xpertzgurtej 13-Oct-17 3:23am    
i already tried with OR instead of And.. OR works fine to prevent data in between existing range but not for overlapping range like 1-70 as i asked in my question
Member 7870345 13-Oct-17 7:07am    
Try that:


IF EXISTS(SELECT 1 FROM HRM.tbAttendanceTimeSlots WHERE (@FromMinutes BETWEEN FromMinutes AND Tominutes) OR (@ToMinutes BETWEEN FromMinutes AND Tominutes))
BEGIN
RETURN -1 --clashing
END
IF EXISTS(SELECT 1 FROM HRM.tbAttendanceTimeSlots WHERE (FromMinutes BETWEEN @FromMinutes AND @Tominutes) OR (ToMinutes BETWEEN @FromMinutes AND @Tominutes))
BEGIN
RETURN -1 --OVERLAP
END


INSERT INTO HRM.tbAttendanceTimeSlots
(
FromMinutes, ToMinutes
)
VALUES
(
@FromMinutes,@ToMinutes
)
RETURN 1
xpertzgurtej 13-Oct-17 7:13am    
it worked..thanks
The simplest way to check for an overlap would be:
SQL
IF EXISTS
(
    SELECT 1 
    FROM HRM.tbAttendanceTimeSlots 
    WHERE @FromMinutes <= ToMinutes 
    AND @ToMinutes >= FromMinutes
)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900