1

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?

Mureinik
  • 277,661
  • 50
  • 283
  • 320
jestges
  • 3,536
  • 24
  • 57
  • 91

3 Answers3

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)
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
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)
Mureinik
  • 277,661
  • 50
  • 283
  • 320
1

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)
Zohar Peled
  • 76,346
  • 9
  • 62
  • 111