在SQL上选择查询参数1或参数2

时间:2014-10-20 18:19:20

标签: sql sql-server stored-procedures parameters where

CREATE PROCEDURE [dbo].[SPPeople]
(
   @Name varchar(50) = null,
   @Status1 char(1) = '0',
   @Status2 char(1) = '0',
   @Status3 char(1) = '0'
)
as
   SELECT 
      People.Name, People.Age 
   FROM 
      People
   WHERE
      (People.Name = CASE WHEN @Name is null THEN People.Name ELSE @Name END) 
      AND
      ((People.Status1 = CASE WHEN @Status1 = '0' THEN People.Status1 ELSE @Status1 END) 
       OR
       (People.Status2 = CASE WHEN @Status2 = '0' THEN People.Status2 ELSE @Status2 END)
       OR
       (People.Status3 = CASE WHEN @Status3 = '0' THEN People.Status3 ELSE @Status3 END))

如果参数@Status1@Status2等于1,则查询应返回必须Status1Status2等于1的寄存器},不依赖于Status3

但是当我将@Status1@Status2作为1传递时,上面的查询会返回所有寄存器。

2 个答案:

答案 0 :(得分:2)

请尝试使用此逻辑:

SELECT p.Name, p.Age 
FROM People p
WHERE (@Name is null OR p.Name = @Name) AND
      (@status1 <> '0' and p.Status1 = @status1 or
       @status2 <> '0' and p.Status2 = @status2 or
       @status3 <> '0' and p.Status3 = @status3
      );

大多数人发现在case子句中理解where表达式比在布尔逻辑中更难理解。

答案 1 :(得分:1)

我认为您可以修改WHERE条件以直接与参数进行比较,例如

WHERE
People.Name = @Name 
AND 
(
People.Status1 = @Status1 
OR
People.Status2 = @Status2 
OR
People.Status3 = @Status3 
)