Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two NULL-able variables in T-SQL

Let's say I have two variables which may be NULL, and I want to check if they are different.

But, I want to:

  • Treat two NULLs as equal (not as NULL).
  • Treat NULL and non-NULL as unequal (not as NULL).

I know I could just write:

DECLARE @v1 int = ...;
DECLARE @v2 int = ...;

IF (
    (@v1 IS NULL AND @v2 IS NOT NULL)
    OR (@v1 IS NOT NULL AND @v2 IS NULL)
    OR @v1 <> @v2
)
    PRINT 'Different!';

But is there a more elegant way?

like image 669
Branko Dimitrijevic Avatar asked Sep 15 '26 18:09

Branko Dimitrijevic


2 Answers

Just to show there are many ways to do it.

IF EXISTS(SELECT @v1 EXCEPT SELECT @v2)
    PRINT 'Different'
like image 106
adrianm Avatar answered Sep 17 '26 13:09

adrianm


There is one more option but I'm not sure whether it'll be more elegant.

IF NOT(NULLIF(@v1, @v2) IS NULL AND NULLIF(@v2, @v1) IS NULL)
PRINT 'Different!';
like image 42
Aleksandr Fedorenko Avatar answered Sep 17 '26 12:09

Aleksandr Fedorenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!