SQL子句和LIKE在where子句中

时间:2011-11-28 11:02:53

标签: sql search switch-statement case sql-like

我一直在打破这个希望,这是可能的

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

我收到错误:

  

关键字'LIKE'附近的语法不正确。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)