存储过程中字段的多个值

时间:2017-03-02 11:17:43

标签: sql sql-server tsql

在这个存储过程中,当@Id为5时,我想获得Id为3和5的记录。我怎样才能实现?

CREATE PROCEDURE spEmployee
    @EmployeeName NVarchar(100),
    @Id int,
AS
    SET NOCOUNT ON

    SELECT * 
    FROM tblEmployees 
    WHERE EmployeeName = CASE 
                            WHEN @EmployeeName IS NOT NULL
                               THEN @EmployeeName 
                               ELSE EmployeeName 
                         END
      AND Department = CASE 
                          WHEN @Id IS NOT NULL
                             THEN @Id 
                             ELSE Id 
                       END
GO

1 个答案:

答案 0 :(得分:0)

这样的事情:

select *
from tblEmployees
where (EmployeeName = @EmployeeName or @EmployeeName is null) and
      (@id is null or
       @id = 5 and Department = 3 or
       Department = @id
      );

通常,在case子句中使用where语句会使代码更难以遵循(它只是布尔运算符的另一个补充)。

case中使用where的两个充分理由是:

  • 因为select中的列使用相同的逻辑。
  • 因为您需要进行顺序评估以防止出现某种错误或确保很少执行昂贵的功能。

否则,最好坚持使用andor