有没有更好的方法来完成这个SQL查询?

时间:2012-03-29 18:16:14

标签: sql tsql

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

WHERE子句有4行,我需要为每个可以传入的参数添加更多的行。其他人可以告诉我是否有更好的方法吗?

编辑:

(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

1 个答案:

答案 0 :(得分:4)

声明另外两个变量以包含min and max values for the MONEY data type,然后将这些值替换为NULL

编辑:由于您希望在两个参数均为NULL时排除结果,我会在查询之前执行条件检查,然后将参数值从NULL更改为@MoneyMin或{ {1}}:

@MoneyMax