Passing Multiple Between Statements To Stored Procedure

不打扰是莪最后的温柔 提交于 2020-03-16 06:26:09

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/45116315/passing-multiple-between-statements-to-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!