Click here to Skip to main content
16,012,116 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I have a table with some bands defined like
BandID | ScoreFrom  | ScoreTo
---------------------------------------
1      |   0        |  95
2      |   96       |  97
3      |   98       |  100   

I would like to add a new score range with some validations like they should not get overlapped with existing ranges.

Like when adding ScoreFrom 97 and ScoreTo 100 it shouldn't allow it to be added.

Also while updating score range it should allow ScoreFrom and ScoreTo in a way so that the range not gets overlapped.

Please help.
Posted
Updated 25-Jan-14 2:14am
v3

1 solution

Assuming your table is called score and BandID is auto-increment, inserting new score range is pretty straight forward:
SQL
CREATE PROCEDURE InsertScore
@newScoreFromValue INT,
@newScoreToValue INT
AS
BEGIN
INSERT INTO score s1 (s1.ScoreFrom, s1.ScoreTo) VALUES (@newScoreFromValue, @newScoreToValue)
WHERE @newScoreFromValue < @newScoreToValue AND NOT EXISTS
(
SELECT * FROM score s2 WHERE s2.ScoreTo >= @newScoreFromValue
)
END


For updating, if I understand your question correctly, there are 3 criteria to consider in order not to "overlap":
SQL
CREATE PROCEDURE UpdateScore 
@BandID INT,
@newScoreFromValue INT,
@newScoreToValue INT 
AS
BEGIN
UPDATE score s1 SET s1.ScoreFrom = @newScoreFromValue, s1.ScoreTo = @newScoreToValue 
WHERE s1.BandID = @BandID AND @newScoreFromValue < @newScoreToValue 
AND NOT EXISTS
(
SELECT * FROM score s2 WHERE s2.BandID <> @BandID AND s2.ScoreFrom BETWEEN @newScoreFromValue AND @newScoreToValue
)
AND NOT EXISTS
(
SELECT * FROM score s3 WHERE s3.BandID <> @BandID AND s3.ScoreTo BETWEEN @newScoreFromValue AND @newScoreToValue
)
AND NOT EXISTS
(
SELECT * FROM score s4 WHERE  s4.BandID <> @BandID AND s4.ScoreFrom <= @newScoreFromValue AND s4.ScoreTo >= @newScoreToValue
)
END

Hope it works. If not, you may want to adapt and modify.
 
Share this answer
 
v2
Comments
Nilesh Agniohtri 25-Jan-14 11:10am    
Thanks..It worked for me with little modifications..
Peter Leow 25-Jan-14 11:12am    
Glad to hear that. It was a great satisfaction.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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