2017-06-29 137 views
-1

您好我正在處理涉及必須使用CASE的查詢。我不斷收到錯誤,但無法弄清楚原因。以下是我所嘗試過的。T-SQL中的SQL Server CASE語句

SELECT 

    CASE 

    when LineItem like '%Apple%' THEN ProductType = 'Apple' 
    when LineItem like '%Orange' THEN ProductType = 'Orange' 
    when LineItem like '%Strawberry' THEN ProductType = 'Red' 
    when ProductType like 'Yellow' THEN ProductType 
    else ProductType = 'White' 

    end as ProductType 

FROM Fruits 

我得到的錯誤是在「=」符號上。 在T-SQL中的WHEN關鍵字之後不可能有兩個不同的列嗎?

+0

擺脫'ProductType ='的。請使用'ELSE'White'' – BJones

+3

請記住'ProductType like'Yellow''充當'=' –

回答

1

嘗試像這樣...

SELECT 
    ProductType = CASE 
         WHEN f.LineItem like '%Apple%' THEN 'Apple' 
         WHEN f.LineItem like '%Orange' THEN 'Orange' 
         WHEN f.LineItem like '%Strawberry' THEN 'Red' 
         WHEN f.ProductType like 'Yellow' THEN f.ProductType 
         ELSE 'White' 
        END 
FROM 
    dbo.Fruits f; 
3

只是語法錯誤。無需Then ProductType = '...'

SELECT 
    CASE 
    when LineItem like '%Apple%' THEN 'Apple' 
    when LineItem like '%Orange' THEN 'Orange' 
    when LineItem like '%Strawberry' THEN 'Red' 
    when ProductType like 'Yellow' THEN ProductType 
    else 'White' 
    end as ProductType 
FROM Fruits