RSS

Monthly Archives: April 2015

Prevent Divide-By-Zero Errors in T-SQL

By Sochinda

NULLIF(expression, expression)

Ex: Column1 / Column2, so when Column2 equal 0 this equation will be error.

How to prvent divide by zero error, we have 2 steps as:

1. using NULLIF

NULLIF(Column2, 0) : it will return NULL when value equal 0

 

2. using ISNULL

ISNULL(NULLIF(Column2, 0), 1) it will return 1 when Column2 value is 0

 

So Column1 /  ISNULL(NULLIF(Column2, 0), 1), it will return Column1 Value when Column2 Value = 0

Advertisements
 
Leave a comment

Posted by on April 21, 2015 in SQL Server