我有一个执行查询的SQL Server 2005存储过程。该存储过程包含三个参数。参数如下:
@StateID as int,
@CountyID为int,
@CityID as int
这些参数用于查询客户列表。如果参数值不为null,我想基本上做一个“AND”。但是,我现在不能做一个if-else。如果参数值不为null,如何添加这些子句。换句话说:
SELECT
*
FROM
Customer c
WHERE
c.StateID=@StateID
-- AND c.CountyID=@CountyID IF @CountyID IS NOT NULL
-- AND c.CityID=@CityID IF @CityID IS NOT NULL
答案 0 :(得分:12)
将这些与OR语句结合起来:
SELECT *
FROM
Customer c
WHERE
c.StateID=@StateID
AND ( c.CountyID=@CountyID OR @CountyID IS NULL )
AND ( c.CityID=@CityID OR @CityID IS NULL )
对于每个参数,如果它为null,则基本上忽略该检查。
答案 1 :(得分:3)
SELECT *
FROM Customer c
WHERE c.StateID=@StateID
AND c.CountyID= ISNULL(@CountyID, c.CountyID)
AND c.CityID = ISNULL(@CityID, c.CityID)
答案 2 :(得分:3)
c.StateID=@StateID
AND
c.CountyID = ISNULL(@CountyID, c.CountyID)
...
使用IF语句
或
c.StateID=@StateID
AND
@CountyID IS NULL OR c.CountyID = @CountyID)
....
或动态SQL
或搜索所有其他问题的SO ...
答案 3 :(得分:1)
SELECT * FROM Customer c WHERE (c.StateID=@StateID) AND ((c.CountyID=@CountyID) OR (@CountyID IS NULL)) AND ((c.CityID=@CityID) OR (@CityID IS NULL))
答案 4 :(得分:1)
没有“正确的方法”,这取决于很多因素,这里有一篇很棒的文章描述了每种方式的PRO和CON都有动态搜索条件:
答案 5 :(得分:0)
一种方式:
SELECT *
FROM Customer c
WHERE c.StateID=@StateID
AND (@CountyID IS NULL OR c.CountyID=@CountyID)
AND (@CityID IS NULL OR c.CityID=@CityID)
另一种方式:
SELECT *
FROM Customer c
WHERE c.StateID=@StateID
AND c.CountyID=ISNULL(@CountyID, c.CountyID)
AND c.CityID=ISNULL(@CityID, c.CityId)
答案 6 :(得分:0)
尝试使用coalesce,我认为这是一种非常优雅,干净的方法:
SELECT *
FROM Customer c
WHERE
c.StateID=@StateID
AND c.CountyID = COALESCE(@CountyID, c.CountyID)
AND c.CityID = COALESCE(@CityID, c.CityID)
(请注意 - 这会过滤掉CountyID或CityID中带空值的记录。)