Search

Friday, August 5, 2011

Workaround for 'Divide by zero error encountered'

Sample Table Structure for demo purpose
CREATE TABLE TestDivideByZero
(
WebSite varchar(50),
NumOfHits int,
Income int
)
Go

Insert dummy records
Insert into dbo.TestDivideByZero values ('a.com', 100, 20)
Insert into dbo.TestDivideByZero values ('b.com', 10, 0)
Insert into dbo.TestDivideByZero values ('c.com', 300, 25)
Insert into dbo.TestDivideByZero values ('d.com', 1300, 225)
Go

Query to produce 'Divide by zero error encountered.' error
Select WebSite, NumOfHits / Income from dbo.TestDivideByZero
Go
This would throw the below error:
Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.
To solve this error 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 TestDivideByZero

Go

No comments:

Post a Comment