问题
Can someone suggest how to add a condition in WHERE
clause of my stored procedure?
CREATE Procedure getAllEmployeesByDeptAndFlag
@Dept int,
@sal int,
@Flag int
AS
if @flag = 1
select *
from employee
where Department = @dept and @sal < 10000
else
select *
from employee
where Department = @dept
Is there any way to simplify above procedure?
回答1:
You could use the or
logical operator to unify both branches of the if
statement:
select * from employee where Department = @dept AND (@flag != 1 OR @sal < 10000)
回答2:
You could define that if you pass in NULL
for @sal
, then the salary is not being checked. No need for an extra @flag
parameter...
CREATE Procedure getAllEmployeesByDeptAndFlag
@Dept int,
@sal int
AS
SELECT
(list of columns)
FROM
dbo.employee
WHERE
Department = @dept
AND (@sal IS NULL OR salary <= @sal)
回答3:
Simply use OR
:
CREATE Procedure getAllEmployeesByDeptAndFlag
@Dept int,
@sal int,
@Flag int
as
select *
from employee
where Department = @dept
and (@flag <> 1 or @sal < 10000)
来源:https://stackoverflow.com/questions/32243493/condition-based-where-clause-sql-server-stored-procedure