Condition based where clause SQL Server stored procedure

ε祈祈猫儿з 提交于 2021-01-28 19:41:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!