Wednesday, April 25, 2007

Workaround for 'Divide by zero error encountered'

Today I just want to write a sample explaining the workaround for 'Divide by zero error encountered.' error in SQL Server.

Sample Table Structure for demo purpose

Create Table dbo.TestDivideByZero
WebSite varchar(50),
NumOfHits int,
Income int

Insert dummy records

Insert into dbo.TestDivideByZero values ('', 100, 20)
Insert into dbo.TestDivideByZero values ('', 10, 0)
Insert into dbo.TestDivideByZero values ('', 300, 25)

Insert into dbo.TestDivideByZero values ('', 1300, 225)

Query to produce 'Divide by zero error encountered.' error

Select WebSite, NumOfHits / Income from dbo.TestDivideByZero

This would throw the below error:

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


Make use of NULLIF function. Like, if the value is 0 then return NULL. For better understanding execute the below query and see it for yourself.

Select WebSite, NumOfHits / NullIf(Income,0) as ColumnName from dbo.TestDivideByZero

Hope this helps!


Delhi_Tamilan said...

hiii... a google search on verizon data services lead me to your blog site.. anyways... quite a informative blog for programmers i guess... but it's not my cup of tea ;)

Anonymous said...

thanks man. it was very helpfull.

AK said...

Excellent tip -been suffering with odbc to excel - all sorted
thanks again

found via Google search

Rand said...

Thanks - this helped with a division where the divisor was never zero (!) - not sure why, regardless the NULLIF fixed it.

virtuesoft said...

Thanks very much, that helped a lot!

Anonymous said...

thank you, thank you, thank you :)

Anonymous said...

Nice Trick - Thanks