Saber
Saber

Reputation: 5720

Passing Multiple Between Statements To Stored Procedure

I have a table full of products, previously we passed a MaxPrice and MinPrice to the stored procedure and selected products with the price between two values.

But now I want to pass multiple range values and want to select products that their prices are between multiple ranges.

Let's say I had a stored procedure like this:

@PriceMin decimal(18, 4) = null,
@PriceMax decimal(18, 4) = null,

... 
WHERE 
    product.Price > @PriceMin 
    AND product.Price < @PriceMax

but now I want to pass multiple range of values based on user selection and have a select like this:

WHERE 
    (product.Price > @PriceMin1 AND product.Price < @PriceMax1)
    OR (product.Price > @PriceMin2 AND product.Price < @PriceMax2)
    OR (product.Price > @PriceMin3 AND product.Price < @PriceMax3)
...

How can I do this?

Upvotes: 3

Views: 693

Answers (1)

DhruvJoshi
DhruvJoshi

Reputation: 17146

I am going to assume that you don't know how many ranges are going to be passed up front, so I'd take up table value parameter to pass data to the stored procedure.

Step 1: Create a TVP

CREATE TYPE dbo.Ranges AS TABLE  
    ( PriceMin  decimal(18, 4), PriceMax   decimal(18, 4) )  

Step 2: Modify your stored procedure parameter list and code

ALTER PROCEDURE usp_selectBasedOnPrice   
    (@rangeList dbo.Ranges READONLY)  
BEGIN
..
-- from product
-- WHERE product.Price > @PriceMin and product.Price < @PriceMax

from product p JOIN @rangeList r
 on p.Price  BETWEEN r.PriceMin  AND r.PriceMax 
END

PS: Note that BETWEEN is better than > and < statement,in this case if your price ranges are inclusive i.e. if you actually need <= and >=; and JOIN is much better than multiple WHERE clauses

Please do note that BETWEEN is equivalent to short hand for <= , >= and not <, >

MS documentation on TVP

Upvotes: 4

Related Questions