Sql Server 2014 Null Value

7

I am a beginner in Sql server, I am doubtful about the following code:

declare @var nvarchar(50) = null

declare @bool bit

if (@var = null)
    set @bool = 1
else
    set @bool = 0

print @bool

The variable @bool returns as 0 , even though I declare the variable @var to be null.

Would not it be to return as 1 ?

    
asked by anonymous 23.09.2016 / 23:06

2 answers

9

This is one of the most particular subtleties of working with database.

This:

if (@var = null) -- Preste atenção aqui
    set @bool = 1
else
    set @bool = 0

It's different than this:

if (@var is null) -- Preste atenção aqui
    set @bool = 1
else
    set @bool = 0

The = null comparison on databases will always be false. This is because null is the absence of value , then is not comparable, unlike checking that the value is null , which causes the return to be 1 .

    
23.09.2016 / 23:15
1

You will not be able to compare a null field value with the = operator, so there is IS NULL

if (@var is null) 
    set @bool = 1
else
    set @bool = 0

There is one thing also that you have to watch your variable @var may still have an Empty value where you could check as follows.

IF (@var IS NOT NULL) OR (LEN(@var) > 0)
    set @bool = 1
else
    set @bool = 0

See more details .

    
05.10.2016 / 14:11