2014-02-07 176 views
0

我試圖在where子句中進行選擇,其中case語句的結果是列名稱。WHERE子句中的case語句的列名作爲條件

這是我已經試過:

declare @lang int -- this is passed to the stored procedure 
declare @productname nvarchar(300) -- this is passed to the stored procedure 

select productid from products where 

    case 
    when @lang = 1 then producten 
    when @lang = 2 then productit 
    when @lang = 3 then productde 
    end product like @productname 

因此,對於英語(@lang = 1)我想:

select productid from products where producten like @productname 

遇到錯誤,但並不能確定是什麼我做錯了。

回答

1

你想句話這樣說:

case when @lang = 1 then producten 
    when @lang = 2 then productit 
    when @lang = 3 then productde 
end like @productname 

或者更明確:

when @lang = 1 and producten like @productname or 
    @lang = 2 and productit like @productname or 
    @lang = 3 and productde like @productname 
+0

很漂亮,謝謝您。完美的作品。 –

0

您可以重新寫入查詢爲:

declare @lang int -- this is passed to the stored procedure 
declare @productname nvarchar(300) -- this is passed to the stored procedure 

select productid from products 
where 1= case when @lang = 1 and @productname like producten then 1 
       when @lang = 2 and @productname like productit then 1 
       when @lang = 3 and @productname like productde then 1 
     end