I was writing a Stored procedure today, and I ran into a problem where if one of the values is null (whether it be from a SELECT statement or whether it be a passed in parameter) my expression would evaluate to false where it ought to evaluate to true.
SET ANSI_NULLS ON; DECLARE @1 INT; DECLARE @2 INT; DECLARE @3 INT; DECLARE @4 INT; SET @1 = 1; SET @2 = NULL; SET @3 = 3; SET @4 = 3; IF ((@1 <> @2) OR (@3 <> @4)) BEGIN SELECT 1; END ELSE BEGIN SELECT 2; END SELECT @1, @2, @3, @4
Returns:
2 1, NULL, 3, 3
I expected it to return:
1 1, NULL, 3, 3
I know I’m missing something simple, anybody have any idea what it is?
Related Question
SQL: Why are
NULLValues filtered Out within thisWHEREclause?
One way of dealing with this is you can wrap your
NULLvalues in a known unexpected value, i.e.-1:Obviously if
-1was a possibility then use a different number. If there is no non-possible value, then you will have to useCASEstatements.A concise way of assigning
NULLvalues to a ‘safe’ value follows:This allows the contional test code to remain ‘clutter-free’.