Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
How can I avoid the divide by zero error in this code?Thanks in advance!
SELECTSUM(MurderMonthCount) AS MonthlyMurderSum,SUM(MurderMonthCleared) AS MonthlyMurderClearedSum,SUM(MurderMonthCleared)/SUM(MurderMonthCount) * 100 AS Test1FROM #tmp1
Lamprey
Master Smack Fu Yak Hacker
4614 Posts
Posted - 2011-10-19 : 16:37:00
One way is to use the NULLIF function:
SELECTSUM(MurderMonthCount) AS MonthlyMurderSum,SUM(MurderMonthCleared) AS MonthlyMurderClearedSum,SUM(MurderMonthCleared)/ NULLIF(SUM(MurderMonthCount), 0) * 100 AS Test1FROM #tmp1
you can also add a COALESCE if you want the result to be 0 and not NULL.