简体   繁体   中英

Is there a better way to accomplish this sql query?

DECLARE @MinPV MONEY            -- PSV
DECLARE @MaxPV MONEY            -- PSV
DECLARE @MinGV MONEY            -- GV
DECLARE @MaxGV MONEY            -- GV
DECLARE @MinLBV MONEY           -- LBV
DECLARE @MaxLBV MONEY           -- LBV
DECLARE @MinRBV MONEY           -- RBV
DECLARE @MaxRBV MONEY           -- RBV
SET @MinPV = 5                  -- PSV
SET @MaxPV = 0                  -- PSV
SET @MinGV = NULL               -- GV
SET @MaxGV = NULL               -- GV
SET @MinLBV = NULL              -- LBV
SET @MaxLBV = NULL              -- LBV
SET @MinRBV = NULL              -- RBV
SET @MaxRBV = NULL              -- RBV

SELECT psv,* 
FROM Distributordetail
WHERE 
    (PSV BETWEEN @MinPV AND @MaxPV) OR          -- Both @MinVol and @MaxVol supplied
    (PSV > @MinPV AND @MaxPV IS NULL) OR        -- Only @MinVol supplied
    (PSV < @MaxPV AND @MinPV IS NULL) OR        -- Only @MaxVol supplied

The WHERE clause has 4 rows, I will need to add MANY more rows for each param that can be passed in. Can anyone else tell me if there is a better way that this?

EDITED:

(PSV BETWEEN @MinPV AND @MaxPV) OR          -- Both @MinVol and @MaxVol supplied
(PSV > @MinPV AND @MaxPV IS NULL) OR        -- Only @MinVol supplied
(PSV < @MaxPV AND @MinPV IS NULL) OR        -- Only @MaxVol supplied
(@MinPV IS NULL AND @MaxPV IS NULL)         -- Neither @MinVol and @MaxVol supplied
(GSV BETWEEN @MinGV AND @MaxGV) OR          -- Both @MinVol and @MaxVol supplied
(GSV > @MinGV AND @MaxGV IS NULL) OR            -- Only @MinVol supplied
(GSV < @MaxGV AND @MinGV IS NULL) OR            -- Only @MaxVol supplied
(@MinGV IS NULL AND @MaxGV IS NULL)         -- Neither @MinVol and @MaxVol supplied

Declare 2 additional variables to contain the min and max values for the MONEY data type , and then substitute these values for NULL .

EDIT: Since you want to exclude the result if both parameters are NULL , I would perform a conditional check before the query before changing the parameter value from NULL to @MoneyMin or @MoneyMax :

DECLARE @MoneyMin MONEY
DECLARE @MoneyMax MONEY

SET @MoneyMin = -922,337,203,685,477.5808
SET @MoneyMax = 922,337,203,685,477.5807

IF (@MinPV IS NOT NULL OR @MaxPV IS NOT NULL)
    SELECT @MinPV = ISNULL(@MinPV, @MoneyMin), @MaxPV = ISNULL(@MaxPV, @MoneyMax)

IF (@MinGV IS NOT NULL OR @MaxGV IS NOT NULL)
    SELECT @MinGV = ISNULL(@MinGV, @MoneyMin), @MaxGV = ISNULL(@MaxGV, @MoneyMax)

SELECT psv,* 
FROM Distributordetail
WHERE 
    (PSV BETWEEN @MinPV AND @MaxPV) OR
    (GSV BETWEEN @MinGV AND @MaxGV)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM