如何在WHERE子句中使用CASE / IF语句?

时间:2019-02-21 06:26:41

标签: sql-server

我有两个声明为@empCode@centerCode的变量。一个中心包含多名员工。我还有一个变量@IsEmployeeBased 现在,如果@IsEmployeeBased = 1,它将使用@empCode,否则它将使用@centerCode。 我的查询就是这样。

    DECLARE @IsEmployeeBased INT = 1;
    DECLARE @empCode INT = 1;
    DECLARE @centerCode INT = 3;
    SELECT * FROM Employee
    WHERE Department = 'Information Tech'
    AND 
    CASE WHEN @IsEmployeeBased = 1 THEN ID = @empCode ELSE CenterCode = @centerCode

这是返回错误,我想是where子句中不允许使用CASE。有什么方法可以使所需的查询正常工作?

以下是示例数据:

CREATE TABLE Employee
(
ID Int,
EmployeeName VARCHAR(25),
Department VARCHAR(25),
CenterCode INT 
)

INSERT INTO Employee VALUES (1, 'Asim', 'Information Tech', 4)
INSERT INTO Employee VALUES (2, 'Ali', 'Information Tech', 2)
INSERT INTO Employee VALUES (3, 'Isaac', 'Information Tech', 3)
INSERT INTO Employee VALUES (4, 'Swagger', 'Information Tech', 4)
INSERT INTO Employee VALUES (5, 'Nadine', 'Information Tech', 2)
INSERT INTO Employee VALUES (6, 'Julie', 'Information Tech', 4)
INSERT INTO Employee VALUES (7, 'Meachum', 'Information Tech', 3)
INSERT INTO Employee VALUES (8, 'Bob Lee', 'Information Tech', 4)

2 个答案:

答案 0 :(得分:1)

CASE表达式(即THENELSE之后的谓词)必须是一个常量值,而不是另一个逻辑表达式。您可以将WHERE子句改写为不使用CASE表达式:

WHERE
    Department = 'Information Tech' AND (
    (@IsEmployeeBased = 1 AND ID = @empCode) OR
    (@IsEmployeeBased <> 1 AND enterCode = @centerCode))

答案 1 :(得分:0)

您还可以尝试通过如下所示创建动态可执行查询。

DECLARE @IsEmployeeBased INT = 0;
DECLARE @empCode INT = 1;
DECLARE @centerCode INT = 3;

DECLARE @Query NVarchar(500)
SET @Query = N'SELECT * FROM Employee WHERE Department = ''Information Tech'''
DECLARE @Where Varchar(250) = ''
IF (@IsEmployeeBased = 1)
BEGIN
    SET @Where += 'AND ID = ' + Convert(char(5), @empCode) +''
END
ELSE IF(@IsEmployeeBased <> 1)
BEGIN
    SET @Where += 'AND CenterCode = ' + Convert(char(5), @centerCode) +''
END
SET @Query = @Query + @Where 

--Select @Query
EXECUTE sp_executesql @Query

也请查看此thread