Tricky If Exists SQL query needed to check overlapped values
I am having a table in SQL server which stores MINIMUM_AMOUNT, MAXIMUM_AMOUNT and CURRENCY_ID. Now I want to frame an SQL query which will check the new values to be inserted are already existing in the table. Ex: My table is having 2 records as follows
RANGE_ID MINIMUM_AMOUNT MAXIMUM_AMOUNT CURRENCY_ID
------------------------------------------------------------
1 3000 9000 3
2 12000 17000 3
Now when user inserts a new record, it should not be in between the values already available
ie : The user should not be able to enter these value pairs
1 ) Min Amount : 4000 , Max Amount : 5000 ,Currency Id : 3
because this range already lies in the first record (RANGE_ID 1)
2) Min Amount : 8000 , Max Amount : 10000,Currency d : 3
开发者_运维知识库 because the minimum amount is already present in the range specified in first record (3000-9000)
3) Min Amount : 8000, Max Amount : 15000 , currency Id=3
because the minimum amount is already present in one range and the maximum amount is also present in another range
4) Min Amount : 2500 , Max Amount : 11000 ,Currency Id=3
because the this range overlaps with the data in first record
User should be able to enter the above range with different Currency ID's.
I am looking for a If Exists query to check this.
Have a look at this
DECLARE @Table TABLE(
RANGE_ID INT,
MINIMUM_AMOUNT FLOAT,
MAXIMUM_AMOUNT FLOAT,
CURRENCY_ID INT
)
INSERT INTO @Table (RANGE_ID,MINIMUM_AMOUNT,MAXIMUM_AMOUNT,CURRENCY_ID) SELECT 1,3000,9000,3
INSERT INTO @Table (RANGE_ID,MINIMUM_AMOUNT,MAXIMUM_AMOUNT,CURRENCY_ID) SELECT 2,12000,17000,3
DECLARE @NewMin FLOAT,
@NewMax FLOAT,
@CurrencyID INT
SELECT @NewMin = 4000,
@NewMax = 5000,
@CurrencyID = 3
SELECT *
FROM @Table
WHERE CURRENCY_ID = @CurrencyID
AND NOT (MINIMUM_AMOUNT > @NewMax OR MAXIMUM_AMOUNT < @NewMin)
This is the reverse of checking
- Full overlap
- Partial Overlap
- Internal Overlap
I think this will do it:
IF EXISTS
(
SELECT *
FROM MinMaxTable mmt
WHERE (mmt.CURRENCY_ID = @currencyID) AND
(@minAmount BETWEEN mmt.MINIMUM_AMOUNT AND mmt.MAXIMUM_AMOUNT) AND
(@maxAmount BETWEEN mmt.MINIMUM_AMOUNT AND mmt.MAXIMUM_AMOUNT)
)
BEGIN
/* New data is within an existing range. */
END
ELSE
BEGIN
/* Partially or completely outside an existing range. */
END;
Use IF NOT EXISTS
to invert the condition.
select 1
from currency_ranges R
where R.CURRENCY_ID = :newCurrency
and (
(R.MINIMUM_AMOUNT <= :newMin and R.MAXIMUM_AMOUNT >= :newMin)
or (R.MINIMUM_AMOUNT <= :newMax and R.MAXIMUM_AMOUNT >= :newMax)
)
This can be used as an EXISTS statement to check for overlaps in the ranges
精彩评论