在这个存储过程中,当@Id
为5时,我想获得Id为3和5的记录。我怎样才能实现?
CREATE PROCEDURE spEmployee
@EmployeeName NVarchar(100),
@Id int,
AS
SET NOCOUNT ON
SELECT *
FROM tblEmployees
WHERE EmployeeName = CASE
WHEN @EmployeeName IS NOT NULL
THEN @EmployeeName
ELSE EmployeeName
END
AND Department = CASE
WHEN @Id IS NOT NULL
THEN @Id
ELSE Id
END
GO
答案 0 :(得分:0)
这样的事情:
select *
from tblEmployees
where (EmployeeName = @EmployeeName or @EmployeeName is null) and
(@id is null or
@id = 5 and Department = 3 or
Department = @id
);
通常,在case
子句中使用where
语句会使代码更难以遵循(它只是布尔运算符的另一个补充)。
在case
中使用where
的两个充分理由是:
select
中的列使用相同的逻辑。否则,最好坚持使用and
和or
。