32

让我们假设有一个具有 3 个参数的存储过程。在所有的可能性中,我希望用一个子句来实现这一点,而不会因为使用太多WHERE而失控......() AND () OR ()

例子:

    //Params
@CITY VARCHAR(100) = NULL,
@GENDER VARCHAR(100) = NULL,
@AGE VARCHAR(100) = NULL

我想你可以IF BEGIN ... END为每个变量(如果存在)使用它,但这会使代码比预期的要长得多。

下面的这种方法不起作用,因为它太长了(大约有 10 个这样的不同字段,但示例只有 3 个。)而且我不确定它是否甚至直接提取了独特的值......

SELECT NAME FROM TABLE 
WHERE (
(CITY=@CITY AND GENDER=@GENDER AND AGE=@AGE)
OR (CITY=@CITY AND GENDER=@GENDER)
OR (GENDER=@GENDER AND AGE=@AGE)
OR (CITY=@CITY AND AGE=@AGE)
OR (CITY=@CITY)
OR (GENDER=@GENDER)
OR (AGE=@AGE)
)

有没有更短更有效的方法来做到这一点?

如果是,则该方法最好也与 JOIN 兼容。

4

5 回答 5

70

除了ISNULL/COALESCE选项,您可以测试参数是否为空:

SELECT NAME  
FROM TABLE  
WHERE  
    (@City IS NULL OR City = @City)
AND 
    (@Gender IS NULL OR Gender = @Gender)
AND 
    (@Age IS NULL OR Age = @Age) 
于 2012-04-17T05:56:58.333 回答
18

那这个呢?

SELECT
    NAME
FROM TABLE 
WHERE CITY = COALESCE(@CITY, CITY)
    AND GENDER = COALESCE(@GENDER, GENDER)
    AND AGE = COALESCE(@AGE, AGE)
于 2012-04-17T05:54:12.910 回答
6

尝试这样的事情:

SELECT NAME 
FROM TABLE 
WHERE 
    City = IsNull(@City, City) AND
    Gender = IsNull(@Gender, Gender) AND
    Age = IsNull(@Age, Age)

或者:

SELECT NAME 
FROM TABLE 
WHERE 
    (City = @City OR @City IS NULL) AND
    (Gender = @Gender OR @Gender IS NULL) AND
    (Age = @Age OR @Age IS NULL)
于 2012-04-17T05:53:43.937 回答
2
SELECT NAME   
FROM TABLE   
WHERE       
  City = case when isnull(@City ,'') = '' then City
                        else @City end
AND      
  Gender = case when isnull(@Gender ,'') = '' then Gender
                        else @Gender end
AND  
  Age = case when isnull(@Age ,0) = 0 then Age
                        else @Age end    
于 2012-04-17T06:34:31.860 回答
1

可能是这样的:

create procedure myProc
    --Params
@CITY VARCHAR(100) = NULL,
@GENDER VARCHAR(100) = NULL,
@AGE VARCHAR(100) = NULL
as

SELECT NAME FROM [TABLE]
WHERE ISNULL(CITY,'')=ISNULL(@CITY,ISNULL(CITY,''))
AND ISNULL(GENDER,'')=ISNULL(@GENDER,ISNULL(GENDER,''))
AND ISNULL(AGE,'')=ISNULL(@AGE,ISNULL(AGE,''))
go

假设 WHERE 子句中的列可以为空,使用 ISNULL 来避免空比较。

于 2012-04-17T05:45:49.427 回答