hello temp11
hello temp11

Reputation: 141

SQL query with 2 where clauses

I am firing a query like

declare @aID varchar(max)='1,2'
declare @TypeId int=23
declare @sql varchar(max)
set @sql = 'SELECT * from Table1
  WHERE 
   AID IN ('+@aID+')
    AND TypeId = @TypeId

  SET NOCOUNT ON;
  begin
  exec(@sql)
  end

Here, I get the result where 'aID' is IN (1,2) and TypeId =23. But I want that result for all rows where aID IN (1,2), even though TypeId !=23. Plus I want results where TypeId =23 and I dont care what 'aID' it is.

Can anyone tell me what should I change ?

Upvotes: 0

Views: 86

Answers (2)

Eric
Eric

Reputation: 703

You need to use OR instead of AND.

SELECT * from Table1
WHERE (AID IN ('+@aID+'))
    OR (TypeId = @TypeId)

With AND, both conditions must be true. With OR, only one (or both) condition needs to be true.

Here's an example.

SELECT UserFirstName, UserLastName
FROM Users
WHERE UserFirstName = 'Bob' AND UserLastName = 'Johnson'

returns

Bob | Johnson

but,

SELECT UserFirstName, UserLastName
FROM Users
WHERE UserFirstName = 'Bob' OR UserLastName = 'Johnson'

returns

Bob | Johnson
Bob | Marley
Tom | Johnson

Upvotes: 0

Mukesh Kalgude
Mukesh Kalgude

Reputation: 4844

Your query is not right. You can change it

set @sql = 'SELECT * from Table1
  WHERE 
   AID IN ('+@aID+') OR TypeId ='+ @TypeId

Upvotes: 3

Related Questions