The following
IF 1 = NULL
BEGIN
SELECT 'A'
END
ELSE
BEGIN
SELECT 'B'
END
Returns the result B as expected
Here's where things get really interesting
IF 1 != NULL
BEGIN
SELECT 'A'
END
ELSE
BEGIN
SELECT 'B'
END
Also returns B
Why is this the case?
Neither IF
statement is true. NULL
is neither equal to something nor not equal to something. Something either IS NULL
or IS NOT NULL
.
Agree with what everyone else has already said. Simply commenting from another angle, if you try setting ansi_nulls
to off, you may get what you expected:
set ansi_nulls off
if 1 = null
select 'a'
else
select 'b' -- Returned
if 1 != null
select 'a' -- Returned
else
select 'b'
More info from Books Online:
When SET ANSI_NULLS is OFF, the Equals (=) and Not Equal To (<>) comparison operators do not follow the ISO standard. A SELECT statement that uses WHERE column_name = NULL returns the rows that have null values in column_name. A SELECT statement that uses WHERE column_name <> NULL returns the rows that have nonnull values in the column. Also, a SELECT statement that uses WHERE column_name <> XYZ_value returns all rows that are not XYZ_value and that are not NULL.
That's ansi_nulls off
explained. However, don't be tempted to simply switch it off because:
In a future version of SQL Server, ANSI_NULLS will always be ON and any applications that explicitly set the option to OFF will generate an error. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.
Follow the below recommendation instead:
For a script to work as intended, regardless of the ANSI_NULLS database option or the setting of SET ANSI_NULLS, use IS NULL and IS NOT NULL in comparisons that might contain null values.
if 1 is null
select 'a'
else
select 'b' -- Returned
if 1 is not null
select 'a' -- Returned
else
select 'b'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With