2016-05-16 139 views
0

試圖在WHERE子句中使用CASE語句,它給我提供了錯誤。我錯過了什麼?CASE語句在WHERE子句不工作我錯過了什麼?

SELECT DISTINCT 
     Commodity, 
     Commodity_ID, 
     [Description], 
     Train, 
     Truck 
FROM dbo.List_Commodity 
WHERE 
     CASE WHEN @Truck = 1 THEN 
      Truck = @Truck 
     WHEN @Train = 1 THEN 
      Train = @Train 
     END 
+1

T-SQL中的CASE是一個**表達式**,它返回**幾個可能的ATOMIC值之一** - 它不是**控制流語句來處理代碼執行.... –

+0

@marc_s - 我在想如何解釋當前的錯誤,很好解釋謝謝! –

回答

0

代替CASE聲明使用AND/OR邏輯做你想要檢索的所有記錄這個

SELECT DISTINCT commodity, 
       commodity_id, 
       [description], 
       train, 
       truck 
FROM dbo.list_commodity 
WHERE (@Truck = 1 
     AND truck = @Truck) 
     OR (@Train = 1 
      AND train = @Train)  

如果當兩個@Truck@Train不等於1然後添加以下條件以上查詢

 OR (@Train <> 1 
      AND @Train <> 1)  
+0

抱歉延誤去了午餐。是的,我認爲我最初有類似的東西,但是當我採用一種解決方案時,每個人都使用Case語句 – Holmes

0

如果您期待THEN truck = @Truck w生病返回truefalse那麼你錯過了MS SQL沒有布爾數據類型和布爾表達式的事實。

0

如果你仍然想使用CASE語句,下面的查詢會有所幫助:

DECLARE @Truck INT = 1 -- 1 is an example 
DECLARE @Train INT = 1 -- 1 is an example 

SELECT DISTINCT 
     Commodity, 
     Commodity_ID, 
     [Description], 
     Train, 
     Truck 
FROM dbo.List_Commodity 
WHERE 1 = 
     (
      CASE 
       WHEN @Truck = 1 AND Truck = @Truck THEN 1 
       WHEN @Train = 1 AND Train = @Train THEN 1 
      END 
     ) 

P.S:請注意,CASE語句只返回應在此相比,它的值。