Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an exclusive OR operator in T-SQL?

Tags:

tsql

This is my statement

IF (@UserName IS NULL AND @EditorKey IS NULL) OR (@UserName IS NOT NULL AND @EditorKey IS NOT NULL) BEGIN
    RAISERROR ('One of @UserName, @EditorKey must be non-null.', 15, 0)
    RETURN
END

What I want is to be able to do something like this:

IF (@UserName IS NOT NULL) XOR (@EditorKey IS NOT NULL) BEGIN
    RAISERROR ('One of @UserName, @EditorKey must be non-null.', 15, 0)
    RETURN
END

For two parameters it isn't that big of a deal, but some procs have three or four where in only one may be passed and the rest should be null.

like image 490
Jonathan Allen Avatar asked May 15 '11 07:05

Jonathan Allen


People also ask

Is T-SQL between inclusive?

The BETWEEN operator is inclusive: begin and end values are included.

Does XOR exist in SQL?

MySQL XOR operator checks two operands (or expressions) and returns TRUE if one or the other but not both is TRUE. MySQL Logical XOR returns a NULL when one of the operands is NULL.

Is in in SQL inclusive?

The SQL BETWEEN condition allows you to easily test if an expression is within a range of values (inclusive). The values can be text, date, or numbers. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.


1 Answers

Not very succinct, but you could expand out the logic like this:

WHERE
    (NOT ((@UserName IS NOT NULL) AND (@EditorKey IS NOT NULL))) AND
    ((@UserName IS NOT NULL) OR (@EditorKey IS NOT NULL))

Or use the bitwise XOR operator (^):

WHERE
    (CASE WHEN (@UserName IS NOT NULL) THEN 1 ELSE 0 END) ^
    (CASE WHEN (@EditorKey IS NOT NULL) THEN 1 ELSE 0 END) = 1

You can use a similar approach where there are three or four parameters, and exactly one must have a value:

WHERE
    (CASE WHEN (@Var1 IS NOT NULL) THEN 1 ELSE 0 END) +
    (CASE WHEN (@Var2 IS NOT NULL) THEN 1 ELSE 0 END) +
    (CASE WHEN (@Var3 IS NOT NULL) THEN 1 ELSE 0 END) +
    (CASE WHEN (@Var4 IS NOT NULL) THEN 1 ELSE 0 END) = 1
like image 135
Chris Fulstow Avatar answered Oct 21 '22 08:10

Chris Fulstow