Today is Monday letting us start this week with interesting puzzle. Yesterday I had also posted a quick question here: SQL SERVER – T-SQL Scripts to Find Maximum between Two Numbers
Run following code:
SELECT SUM(data) FROM (SELECT NULL AS DATA) t
It will throw following error.
Msg 8117, Level 16, State 1, Line 1
Operand data type void type is invalid for sum operator.
I can easily fix if I use ISNULL Function as displayed following. ISNULL function replaces NULL with the specified replacement value. The value of check_expression is returned if it is not NULL; otherwise, replacement_value is returned after it is implicitly converted to the type of check_expression, if the types are different. NULLIF function returns a null value if the two specified expressions are equal. NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.
SELECT SUM(data) FROM (SELECT ISNULL(NULL,0) AS DATA) t
The above script will not throw an error. However, there is one more method how this can be fixed.
Can you come up with another method which will not generate error?
Reference: Pinal Dave (https://blog.sqlauthority.com)