假设有一个存储过程有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兼容。
答案 0 :(得分:50)
除ISNULL
/ COALESCE
选项外,您可以测试参数为null:
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)
答案 1 :(得分:11)
这是怎么回事?
SELECT
NAME
FROM TABLE
WHERE CITY = COALESCE(@CITY, CITY)
AND GENDER = COALESCE(@GENDER, GENDER)
AND AGE = COALESCE(@AGE, AGE)
答案 2 :(得分:4)
尝试这样的事情:
SELECT NAME
FROM TABLE
WHERE
City = IsNull(@City, City) AND
Gender = IsNull(@Gender, Gender) AND
Age = IsNull(@Age, Age)
OR:
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)
答案 3 :(得分:1)
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
答案 4 :(得分:0)
可能是这样的:
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避免空值比较。