1

Im trying to compare 2 values -1 is null and other is numeric, but it somehow equals to "equal"

declare @value1 int;
declare @value2 int;
select @value1 = null
select @value2 = 1
if (@value1 <> @value2)
    print 'not equal'
else 
    print 'equal'

Result: Equal

0

2 Answers 2

9

You cannot compare NULL values, neither with = nor <> since NULL means undefined.

Use IS if you want to know if a values is NULL, you can use:

IF ( ( @value1 IS NULL 
       AND @value2 IS NULL ) 
      OR (( @value1 IS NOT NULL 
            AND @value2 IS NOT NULL 
            AND @value1 = @value2 )) ) 
  PRINT 'equal' 
ELSE 
  PRINT 'not equal' 

See: What if null if null is null null null is null?

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

Comments

2

NULL fails all comparisons therefore if(null <> @value) is false.

Per MSDN

When SET ANSI_NULLS is ON, all comparisons against a null value evaluate to UNKNOWN.

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.