根据条件在 SQL 中放置 where 子句条件?

阿曼·拉比

我有一个带有两个参数的存储过程,它返回给我的员工列表。我的存储过程工作正常,但我需要根据条件在我的 where 子句中添加条件。以下是我的存储过程:

create procedure sp_GetEmployees

   @BranchId int = 0,
   @DeptId int = 0

as

Begin

 if(@BranchId > 0 and @DeptId > 0)
  select * from Employees where BranchId = @BranchId and DeptId = @DeptId
 else if (@BranchId > 0 and @DeptId = 0)
  select * from Employees where BranchId = @BranchId
 else if (@BranchId > 0 and @DeptId = 0)
  select * from Employees where DeptId = @DeptId
 else
  select * from Employees

End

这是一个简单的案例,但我有更复杂的场景,我传递 8 到 10 个参数并为它们设置条件会很头疼。我需要在一个选择语句中简化它。我尝试了以下但当然,这是不正确的:

if(@BranchId > 0 or @DeptId > 0)
select * from Employees where
     case @BranchId when 0 then ''
     else BranchId = @BranchId 
     End
else
select * from Employees  

我怎样才能简化它?

妓女

您可以简化您的查询,如下所示。

SELECT * 
FROM   Employee 
WHERE  ( Branchid = @BranchId 
          OR @BranchId = 0 ) 
       AND ( Deptid = @DeptId 
              OR @DeptId = 0 ) 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章