There are OR
and AND
operators in T-SQL. AND
means when two conditions are true and OR
means if only first condition is true, if only second condition is true or if both conditions are true.
But I need something like XOR
which is like OR
but if both are true, the WHERE
condition is not applied.
Example :
select *
from [Table]
where Id in (@FromId) XOR TypeId = @TypeId
My question is: how should I write this query so if Id in (@FromId)
found, it doesn't check TypeId =@TypeId
and if Id in (@FromId)
isn't found, it checks for TypeId =@TypeId
.
I know that I can write this for solving the problem :
select * from [Table] where Id in (@FromId)
if @@ROWCOUNT =0
select * from [Table] where TypeId =@TypeId
but I want write it in one query, for simplicity, performance, less code ,....
Thanks in advance.
Basically an XOR can be expressed in terms of AND and OR as follows:
(cond1 AND NOT cond2) OR (NOT cond1 AND cond2)
So your query can be written as
select *
from [Table]
where (Id in (@FromId) AND TypeId <> @TypeId) OR (Id NOT IN (@FromId) AND TypeId = @TypeId)