I am writing a trigger that does
IF (@A <> @B) ...
but this will not work for NULL values ββon @A or @B. This is usually done
IF (@A <> @B) OR (@A IS NOT NULL AND @B IS NULL) OR (@A IS NULL AND @B IS NOT NULL)
but this implies up to 9 comparisons versus 1!
I could do
SET ANSI_NULLS OFF
but apparently this is not recommended (and be deprecated).
So what is the best solution for this? Just take 9 comparisons for a simple check of inequality, when should it be 1? A trigger is not performance critical, but it must be fast. When batch loading, this can significantly slow it down.
TIME TESTS
Below are the results of a performance test that checks inequality a million times, so that in 90% of cases the values ββare not equal, 10% of the time each value can be zero.
IF (@A <> @B) OR (@A IS NULL AND @B IS NOT NULL) OR (@A IS NOT NULL AND @B IS NULL)
Result: average 3848 ms
IF (ISNULL(@A, 0) <> ISNULL(@B, 0))
Result: average 3942 ms
IF (@A = @B) GOTO Equal ELSE IF @A IS NULL AND @B IS NULL GOTO Equal
Result: average 4140 ms
IF EXISTS (SELECT @A EXCEPT SELECT @B)
Result: average 7795 ms
Times don't matter much, it's the relative difference that matters. Obviously, the classic approach is the fastest . MSSQL is probably internally optimized for this type of validation.
Testing on a MacBook Pro (Intel Core 2 Duo, 2.4Ghz, 8 GB of RAM in a virtual VM running on MSSQL 2008 Express).