Reputation: 1236
Is there an XOR operator or equivalent function in SQL Server (T-SQL)?
Upvotes: 67
Views: 129823
Reputation: 1230
<>
is generally a good replacement for XOR wherever it can apply to booleans.
Upvotes: 2
Reputation: 2050
From your comment:
Example: WHERE (Note is null) ^ (ID is null)
you could probably try:
where
(case when Note is null then 1 else 0 end)
<>(case when ID is null then 1 else 0 end)
Upvotes: 1
Reputation: 353
MS SQL only short form (since SQL Server 2012):
1=iif( a=b ,1,0)^iif( c=d ,1,0)
Upvotes: 20
Reputation: 1435
As clarified in your comment, Spacemoses, you stated an example: WHERE (Note is null) ^ (ID is null). I do not see why you chose to accept any answer given here as answering that. If i needed an xor for that, i think i'd have to use the AND/OR equivalent logic:
WHERE (Note is null and ID is not null) OR (Note is not null and ID is null)
That is equivalent to:
WHERE (Note is null) XOR (ID is null)
when 'XOR' is not available.
Upvotes: 23
Reputation: 5213
Using boolean algebra, it is easy to show that:
A xor B = (not A and B) or (A and not B)
A B | f = notA and B | g = A and notB | f or g | A xor B
----+----------------+----------------+--------+--------
0 0 | 0 | 0 | 0 | 0
0 1 | 1 | 0 | 1 | 1
1 0 | 0 | 1 | 1 | 1
1 1 | 0 | 0 | 0 | 0
Upvotes: 43
Reputation: 1436
The xor operator is ^
For example: SELECT A ^ B
where A and B are integer category data types.
Upvotes: 5
Reputation: 776
There is a bitwise XOR operator - the caret (^), i.e. for:
SELECT 170 ^ 75
The result is 225.
For logical XOR, use the ANY keyword and NOT ALL, i.e.
WHERE 5 > ANY (SELECT foo) AND NOT (5 > ALL (SELECT foo))
Upvotes: 62
Reputation: 135111
It is ^
http://msdn.microsoft.com/en-us/library/ms190277.aspx
See also some code here in the middle of the page How to flip a bit in SQL Server by using the Bitwise NOT operator
Upvotes: 2