Sql 要添加到WHERE子句的CASE语句?

Sql 要添加到WHERE子句的CASE语句?,sql,sql-server,Sql,Sql Server,如何在SQL Server中使用此case语句 declare @isnot tinyint select @isnot = 1 select top 100 * from Employee where EmployeeID > 1 and case when @isnot = 1 then (EmployeeName = 'Brian') else (EmployeeName = 'Anie') end

如何在SQL Server中使用此case语句

declare @isnot tinyint
select @isnot = 1

select top 100 * 
from Employee 
where EmployeeID > 1  
  and case 
         when @isnot = 1 
            then (EmployeeName = 'Brian') 
            else (EmployeeName = 'Anie')
end
如果查询是这样的呢

declare @isnot tinyint
select @isnot = 1 -- option : 0 and 1

select top 100 * 
       from Employee 
        where EmployeeID > 1 
        case 
            when @isnot = 1 
            then (and EmployeeName = 'Brian') 
            else '' -- blank
    end

我不想使用任何子查询或类似的东西。

因为您使用的是值二进制检查(代码只关心值1或不关心值1),您也可以使用它来缩短语法

declare @isnot tinyint
select @isnot = 1

SELECT top 100 * 
FROM Employee 
WHERE 
EmployeeID > 1  AND 
EmployeeName =
             CASE @isnot 
             WHEN 1 
             THEN 'Brian' 
             ELSE 'Anie'
             END
DECLARE @isnot tinyint = 1

SELECT TOP 100 * 
FROM Employee 
WHERE EmployeeID > 1 AND
EmployeeName = IIF(@isnot = 1, 'Brian', 'Anie')

语法是关键,您需要END来完成CASE语句,并且EmployeeName开始,因此:

或者

SELECT TOP 100 * FROM Employee WHERE EmployeeID > 1
AND EmployeeName = CASE WHEN @isnot = 1 THEN 'Brian' ELSE 'Anie' END

无案例陈述

WHERE EmployeeID > 1 
    AND (EmployeeName == 'Brian' AND @isnot = 1
        OR EmployeeName == 'Anie')

您只是缺少结尾处的
END
。。。您需要使用
end
@Aominè结束
CASE
语句。我想在where语句中添加CASE,这样它会自动添加Employee='Bran'或Employee='Anie'。通常在where和ON子句中使用
/
而不是CASE表达式更好。谢谢您的回答,但我在这个帖子中真正的问题是关于第二个问题(@isnot=1和EmployeeName='Brian')或@isnot1
WHERE EmployeeID > 1 
    AND (EmployeeName == 'Brian' AND @isnot = 1
        OR EmployeeName == 'Anie')