Search code examples
sqlsql-servert-sqlconstraintsxor

SQL Server Null Logical XOR


I'm creating a constraint on a (Microsoft) Sql Server 2008 table. I have two columns that are different datatypes. One column must be null at all times, but not both (A logical exclusive OR/XOR). I have a working expression currently.

(@a is null or @b is null) and not (@a is null and @b is null)

My question is Is there a cleaner or shorter way to write this code?

To test it you can use this code...

declare @a int
declare @b varchar(5)

set @a=1
set @b='XXXXX'

if (@a is null or @b is null) and not (@a is null and @b is null)
  select 'pass'
else
  select 'fail'

Solution

  • I would prefer

    if (@a is null and @b is not null) or (@a is not null and @b is null)
    

    It is a little clearer in my opinion