Condition on null does not work with =

What do you expect from the following code? Will the block inside if be executed?


IF ( @ID != NULL )
  BEGIN
      UPDATE inventory
      SET    count = 5
      WHERE  id = @ID
  END 

The statments inside If will never be executed because it will always evaluate false. The reason it equal (=) operator is not compatible with NULL. To compare NULL value, use IS operator. To fix the above we can write


IF ( @ID IS NOT NULL )
  BEGIN
      UPDATE inventory
      SET    count = 5
      WHERE  id = @ID
  END 

Or we can use ISNULL operator to convert NULL into a value


IF ( Isnull(@ID, 0) = 0 )
  BEGIN
      UPDATE inventory
      SET    count = 5
      WHERE  id = @ID
  END 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*