declare @test int
declare @test2 int = 3
select case when @test != @test2 then 1 else 0 end
select case when @test = @test2 then 1 else 0 end
The result is always 0. Can someone explain this?
declare @test int
declare @test2 int = 3
select case when @test != @test2 then 1 else 0 end
select case when @test = @test2 then 1 else 0 end
The result is always 0. Can someone explain this?
You haven't set a value for @test
yet, there for it is NULL
.
@test
will never be equal or not equal to @test2
, since any comparison against NULL
will be false.
This behavior is controlled by the ANSI_NULLS set option. In fact if you SET ANSI_NULLS OFF you will get a 1 for the first select.
NULL is a special value, it is an unknown value. You can read your queries like this:
Select a value, when an unknown value is not equal to 3 Select a value, when an unknown value is equal to 3
Since the value is unknown it may or may not match, so you can't assume that it's not equal, as it is possible that they are equal. Since your comparing an unknown value it's like your comparing all possible values, and since there is one possible value that invalidates it the statement is false.
If I am not mistaken when you declare a variable without a default value the value assigned is null. So in your two SELECT CASE statements you are comparing null to an actual value and the comparison will not work.