CAST/CONVERT makes expressions nullable

I came upon this issue when I was building some views to support legacy integrations to an app that I was refactoring. The view is supposed to have exactly the same column definitions as a table in the old database that I am redesigning, so to make SSIS packages and other integrations run smoothly, I want the view’s columns to have the same datatypes, nullability, etc.

But there are some gotchas to watch out for with CAST and CONVERT.

Using NULLIF() to avoid division by zero

When you perform divisions, you need to make sure that the divisor, the number to the right of the division operator, isn’t zero. If it is, you will end up with a division-by-zero error message:

Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.

Dividing by NULL, however, doesn’t. So to avoid division-by-zero errors, simply use NULLIF() to replace zeros in the divisor with a NULL value.