1

I must to check if two values, X and Y are different. If both are null, they must be considered as equal.

The unique way I found is:

select 1 as valueExists 
where  (@X is null and @Y is not null) 
    or (@Y is null and @X is not null) 
    or (@X <> @Y)

Is there a smart way to write this expression? Thanks!

5
  • SELECT 1 as valuesDifferent WHERE EXISTS (SELECT @X EXCEPT SELECT @Y). The answer you accepted doesn't work correctly for SET @X = ''; SET @Y = NULL Commented Jul 4, 2014 at 20:38
  • @Martin Smith could you explain what your code does please? Commented Jul 5, 2014 at 8:17
  • where exists returns true if the sub query it contains returns a row. This will happen in this case if the two values are distinct. Treating null as a distinct value Commented Jul 5, 2014 at 8:23
  • @MartinSmith That duplicate is not the same question and the answer in the duplicate is not the same answer you post in comment. I suggest you post that as an answer. Voting to reopen. Commented Jul 5, 2014 at 14:05
  • Well actually the answer is basically the same. Maybe not the question then! Commented Jul 5, 2014 at 17:22

4 Answers 4

3

I think you could use COALESCE for that

WHERE coalesce(@X, '') <> coalesce(@Y, '')

What it does it returns an empty string if one of variables is null, so if two variables are null the two empty strings become equal.

Sign up to request clarification or add additional context in comments.

Comments

1

I typically use a technique I picked up from here

SELECT 1 AS valuesDifferent
WHERE  EXISTS (SELECT @X
               EXCEPT
               SELECT @Y) 

WHERE EXISTS returns true if the sub query it contains returns a row. This will happen in this case if the two values are distinct. null is treated as a distinct value for the purposes of this operation.

Comments

0

You could try using NULLIF like this:

WHERE NULLIF(@X,@Y) IS NOT NULL OR NULLIF(@Y,@X) IS NOT NULL

Comments

-1

You can use ISNULL

WHERE ISNULL(@X,'') <> ISNULL(@Y,'')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.