April 20, 2012

T-SQL divide by zero

I've spent so much time in SharePoint and Reporting Services lately that I had to remind myself the syntax for handling divide by 0 in T-SQL.

Belle's SQL Musings blog (nice title) does a good job explaining some simple options using the NULLIF function.

The tool-tip found in SQL 2008 Management Studio also does a good job of explaining that it "Returns a null value if the two specified expressions are equal."  Format: NULLIF(expression1, expression2).  So basically I did this:

my number / NULLIF(my crazy expression, 0)