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
,则查询应返回必须Status1
或Status2
等于1
的寄存器},不依赖于Status3
。
但是当我将@Status1
和@Status2
作为1
传递时,上面的查询会返回所有寄存器。
答案 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
)