Is there an exclusive OR operator in T-SQL?

前端 未结 3 1651
既然无缘
既然无缘 2021-02-12 15:49

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,         


        
相关标签:
3条回答
  • 2021-02-12 16:22

    As a cheat, you can do:

    If @UserName+@EditorKey is null and coalesce(@UserName,@EditorKey) is not null
    

    It's shorter, but that may be the only thing it has going for it.

    0 讨论(0)
  • 2021-02-12 16:39

    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
    
    0 讨论(0)
  • 2021-02-12 16:43

    There's a bitwise XOR, but it's not necessarily what you want:

    http://msdn.microsoft.com/en-us/library/ms190277.aspx

    In your particular case, I find it more immediate to rewrite it like so:

    IF (@UserName IS NULL) = (@EditorKey IS NULL) BEGIN
    
    0 讨论(0)
提交回复
热议问题