2017-10-13 220 views
1

如何在SQL Server中使用此case語句?CASE語句添加到WHERE子句中?

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 

我不想使用任何子查詢或類似的東西。

+0

你只是缺少'END'末......你需要結束與'END' –

+0

了'CASE'聲明@青峯我想補充的情況下,以我的WHERE語句,因此將會被自動添加員工=' Bran'或Employee ='Anie' – Richard

+0

在AND和ON子句中使用'AND' /'OR'代替case表達式通常要好得多。 – jarlh

回答

2
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 
+0

感謝您的回答,但我在這個線程真正的問題是關於第二個問題 – Richard

+0

(@isnot = 1 AND EmployeeName =「布萊恩」)或@isnot <> 1 –

0

由於您使用的是二進制值檢查(代碼只在乎值1或不是1)您也可以使用IIF這使得較短的語法。

DECLARE @isnot tinyint = 1 

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

語法是關鍵,這一點,你需要年底完成CASE語句,也EmployeeName開始與...所以:

無論是

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

OR

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

無案例說明

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