2011-11-28 60 views
4

我已經打破我的頭在這個希望有可能SQL案例,並喜歡在where子句

declare @locationType varchar(50); 
declare @SearchTerm NVARCHAR(100); 

SELECT column1, column2 
FROM whatever 
WHERE 
CASE @locationType 
    WHEN 'location' THEN account_location LIKE @SearchTerm 
    WHEN 'area' THEN Area LIKE @SearchTerm 
    WHEN 'division' THEN xxx_location_division LIKE @SearchTerm 
END 

我複製的代碼形式另一個相關的帖子here

我得到的錯誤:

Incorrect syntax near the keyword 'LIKE'.

回答

6
declare @locationType varchar(50); 
declare @SearchTerm NVARCHAR(100); 

SELECT column1, column2 
FROM whatever 
WHERE 
    (@locationType = 'location' AND account_location LIKE @SearchTerm) 
OR 
    (@locationType = 'area' AND Area LIKE @SearchTerm) 
OR 
    (@locationType = 'division' AND xxx_location_division LIKE @SearchTerm) 

確保@SearchTerm開始與/結束與% - >或使用'%' + @SearchTerm + '%'

有關LIKE operator的更多信息。

---更新----

SELECT column1, column2 
FROM whatever 
WHERE 
(
    CASE @locationType 
    WHEN 'location' THEN account_location 
    WHEN 'area' THEN Area 
    WHEN 'division' THEN xxx_location_division 
    END 
) LIKE @SearchTerm 
+0

所以'LIKE','WHERE'和'CASE'不一起?你的意思是以'/'開始並以'%'結尾? – Deeptechtons

+0

==在sql中不起作用。 –

+0

是的,我的錯==。如果你在尋找「NEW」的地方,那麼「@ SearchTerm」應該是「NEW%」。 –

0

如果沒有需要檢查字符串插圖中,那麼你可以做的伎倆象下面這樣:

SELECT column1, column2 
FROM whatever 
WHERE @SearchTerm LIKE 
CASE @locationType 
    WHEN 'location' THEN account_location 
    WHEN 'area' THEN Area 
    WHEN 'division' THEN xxx_location_division 
END 

或者,你可以這樣做:

SELECT column1, column2 
FROM whatever 
WHERE 
    (@locationType = 'location' AND account_location LIKE @SearchTerm) 
OR 
    (@locationType = 'area' AND Area LIKE @SearchTerm) 
OR 
    (@locationType = 'division' AND xxx_location_division LIKE @SearchTerm) 
+0

我搜索的列基於'@ searchtype'。這裏沒有明確提到,但@locationType是這裏使用的變量 – Deeptechtons

+0

,所以在這裏你可以用searchType替換變量@locationType。 –