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
  • 297,002
  • 52
  • 306
  • 350
jestges
  • 3,686
  • 24
  • 59
  • 95

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
  • 732,580
  • 175
  • 1,330
  • 1,459
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
  • 297,002
  • 52
  • 306
  • 350
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
  • 79,642
  • 10
  • 69
  • 121