简体   繁体   中英

OR statement isn't working

New to Sqlserver and I'm doing something like

select *
from table1
where field1 IN ('textvalue1','textvalue2') OR field2 IN ('textvalue1','textvalue2')

It's not working at all... no syntax errors and an AND statement works fine. I've tried enclosing it in parenthesis as well.

According to all the comments, you must not have the values in your data that you think you do. Here is a reproducible example of it working.

declare @table table (field1 varchar(64), field2 varchar(64))
insert into @table
values
('a','b'),
('c','d'),
('e','f'), --only row that won't return with logic below
('g','h'),
('i','j')

select *
from @table
where field1 in ('a','c') or field2 in ('h','j')

RETURNS

+--------+--------+
| field1 | field2 |
+--------+--------+
| a      | b      |
| c      | d      |
| g      | h      |
| i      | j      |
+--------+--------+

OF NOTE SQL Server ignores trailing spaces for equality operators, but leading spaces will fail. Thus, you may need to use LTRIM() if you have leading space.

declare @table table (field1 varchar(64), field2 varchar(64))
insert into @table
values
('a    ','b'),
('c    ','d'),
('e    ','f'),
('g','    h'),
('i','    j')

select *
from @table
where ltrim(field1) in ('a','c') or ltrim(field2) in ('h','j')

Either you are passing name as Variable then use ' YYY' or if you are fetching using an inner query then pass the sub query inside the IN clause as mentioned below.

SELECT * 
FROM PERSON 
WHERE NAME IN ('jill') OR NAME IN (SELECT NAME FROM PERSON WHERE NAME ='jake');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM