2011-11-28 59 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。 –