I am having a bit of difficulty understanding how t-sql treats null values.
As a C# guy, I tend to want to do
IF(@myVar != null)...
But, this doesn’t ever appear to run my code. So I do
IF(@myVar is not null)
Whats the difference?
Second, the way addition works is unclear. Let’s say I have
declare @someCount int, @someFinalResult int
--Select that returns null
SELECT @someCount = columnName from tableName where someColumn = someValue
Then if I do
SET @someFinalResult = @someCount + 1--I seem to get NULL if I had null + something
But, if I first
declare @someCount int, @someFinalResult int
--FIRST SET DEFAULT TO 0
SET @someCount = 0
--Select that returns null
SELECT @someCount = columnName from tableName where someColumn = someValue
Now, @someCount defaults to 0, it’s not actually set equal to NULL even if the result is null. Why?
When you deal with NULL in SQL Server you basically work with 3-value logic with all the implications.
So in your example
IF(@myVar != null)vsIF(@myVar is not null)It basically boils down to the question what is the difference between:
@myVar = nullvs@myVar is null@myVar = nullwill always evaluate to null as what you are asking is:As you do not know what the UNKNOWN is this question cannot by answered yes, or no so it evaluates to UNKNOWN
The last one may be a bit tricky but just imagine that you have 2 boxes with apples and you do not know neither how many apples are in box1 one nor in box2 so asking:
so the answer is
I do not knowthe second one
@myVar is nullis different as it is like askingso the difference is that you specifically ask “is it true that the value stored in the variable is UNKNOWN?”, so