where 子句中的 SQL Case 和 LIKE

标签 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 .

我收到错误:

Incorrect syntax near the keyword 'LIKE'.

最佳答案

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

关于where 子句中的 SQL Case 和 LIKE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8294852/

相关文章:

mysql - MySQL 可以将存储的 UTC 时间转换为本地时区吗?

php - 如何在多维数组的所有列中搜索索引

arrays - 为什么在 HashMap 中查找项目比在数组中查找项目更快?

Swift:带有 switch 语句的嵌套枚举

C: switch 中需要整数表达式而不是 XY

css - 页面特定产品模板 opencart 2.0.1.1

mysql - 如果符合任何条件,则显示结果?

mysql - 数据库设计:多表和外键

SQL over 子句 - 将分区划分为编号的子分区

search - 是否可以在typo3 solr 搜索结果中向非登录用户显示访问限制页面?