SQL Server 2005:将 OR 运算符与 LIKE 运算符一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7975301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:05:56  来源:igfitidea点击:

SQL Server 2005 : using OR operator with LIKE operator

sqlsql-serversql-server-2005

提问by simranNarula

How can I use LIKEoperator with the ORoperator in SQL Server 2005? For example:

如何将LIKE运算符与ORSQL Server 2005 中的运算符一起使用?例如:

SELECT * 
  FROM table 
 WHERE column_name LIKE '%boo%' OR '%bar%' 

This does not seems to work !

这似乎行不通!

EDIT 1: RESPONSE TO FIRST ANSWER POSTED:

编辑 1:对发布的第一个答案的回应:

Cool, that works ! but I just found for the first time that your order conditions do not work with like ... I want to ask is this normal or am I making a mistake? please see below to see what I mean

很酷,很管用!但我第一次发现你的订单条件不适合......我想问一下这是正常的还是我犯了错误?请参阅下文以了解我的意思

select * 
from <table> 
where col_name = 'VAL-QWE' 
      AND scenario like '%xxx%'
      OR scenario like '%yyy%'

if you execute this query, sql server does not cares for col_name = 'VAL-QWE'condition at all, it just looks at the like condition ?

如果你执行这个查询,sql server 根本不关心col_name = 'VAL-QWE'条件,它只看类似的条件?

回答by

select * 
from table where 
column_name like '%boo%' 
or column_name like '%bar%'  

You need to repeat what the condition is being tested on. In this case, you need to repeat column_namein your second conditional likeclause.

您需要重复正在测试的条件。在这种情况下,您需要column_name在第二个条件like子句中重复。

The likeor any conditional test does not persist from the previous statement/test.

like或任何条件测试不会从先前的语句/测试中持续存在。

回答by dsteele

You have totally changed the meaning of your question by your editing, not a good thing to do!

您通过编辑完全改变了您问题的含义,这不是一件好事!

In your modified example, the 'AND' is evaluated before the 'OR' , so your sql is doing the following:

在您修改的示例中, 'AND' 在 'OR' 之前进行评估,因此您的 sql 正在执行以下操作:

select * from <table> where (col_name = 'VAL-QWE' AND scenario like '%xxx%') or scenario like '%yyy%'

but what I think you want is

但我认为你想要的是

select * from <table> where col_name = 'VAL-QWE' AND (scenario like '%xxx%' or scenario like '%yyy%')

回答by rakesh

Plain and simple use sql regexp:

简单明了的使用sql正则表达式:

select * from <table> where col_name = 'VAL-QWE' AND scenario REGEXP 'xxx|yyy';