如何搜索多个字符串或字符在字段中的SQL(How to search multiple string

2019-10-29 11:47发布

我使用SQL Server和我有一个有两个字段的表

  1. 名称
  2. 描述

我要选择那些行包含以下字符串

( '$', '%', 'AC CD', 'HJD OIH')

我使用它像这样

select Name , description from table_name 
where Description like any (' %$%',' %[%]%','%ac cd%' , '%hjd oih%')

现在它给人错误,当我运行这个

Incorrect syntax near the keyword 'any'.

谢谢 ,

Answer 1:

如果你有multiple patterns来进行搜索,那么它最好创建一个derived tabletemporary table来存储patterns

DECLARE @patterns TABLE  (
pattern VARCHAR(20)
);

INSERT INTO @patterns VALUES ('%$%'), ('%[%]%'), ('%ac cd%');

SELECT a.* FROM table_name a JOIN @patterns p ON (a.Description LIKE p.pattern);

如果你有多个列比较只需添加表达ON子句

SELECT a.* FROM table_name a JOIN @patterns p ON (a.Description LIKE p.pattern)
OR (a.Column2 like p.pattern);

更新:使用视图

CREATE VIEW PatternSearch
AS
 WITH Patterns (Patterns)
  AS
  (
     Select  '%Tool%'
     union all
     Select '%Sale%'
     union all
     Select  '%ac cd%'
  )
   SELECT a.* FROM table_name a JOIN Patterns p ON (a.Description LIKE p.pattern)

GO

未经测试,但你可以做这样的

资源



文章来源: How to search multiple strings or chars in a field in sql