Integers are higher in data type priority , so varchar is converted to int. An empty string converted to int, 0 , and from there it is pretty obvious ( 0 == 0 ).
0 == 0 , so NULLIF(0, 0) => NULL (since NULLIF(a, b) returns NULL iff a == b )
When you do nullif(convert(varchar,0),'') , you just do NULLIF('0', '') . Obviously, a string containing only 0 and an empty string is not equal, so you get 0 .
A more detailed explanation is that two different types cannot be compared. You cannot compare a string with an integer, or with a string and with a floating point, or with an integer and with a floating point, or so on. This means that in order to compare different types, there must be some implicit casting rule. In this case, it happens that if you compare the string (well, technically varchar) and int, varchar is converted to int implicitly. This is much easier to see if you consider the following:
SELECT CONVERT(INT, ''); IF '' = 0 SELECT 'Equal' ELSE SELECT 'Not equal';
As you will see, the conversion gives an integer value of 0. In addition, this leads to a comparison between two estimates with true.
Corbin
source share