SQL Server - Can any one tell me why i get the following error on this SQL script

Asked By jason
04-Oct-11 09:38 PM
UPDATE s
SET 
s.mix_ty = CAST(s.net_sales_ty AS DECIMAL(19,5)) / CAST(b.net_sales_ty AS DECIMAL(19,5)),
s.mix_ly = CAST(s.net_sales_ly AS DECIMAL(19,5)) / CAST(b.net_sales_ly AS DECIMAL(19,5))
FROM #sales s
INNER JOIN (
SELECT division_code, SUM(net_sales_ty) AS net_sales_ty, SUM(net_sales_ly) AS net_sales_ly
FROM #sales
GROUP BY division_code
) b ON s.division_code = b.division_code

error 'Divide by zero error encountered

Is there anything wrong with the syntax above. Its the only part in my store proc that is failing. 
  Anoop S replied to jason
04-Oct-11 09:45 PM
This error is caused by performing a division operation wherein the denominator or the divisor is 0.  This error is not encountered when the denominator or divisor is NULL because this will result to a NULL value.
Check what values you are getting in CAST(b.net_sales_ty AS DECIMAL(19,5)), and CAST(b.net_sales_ly AS DECIMAL(19,5)), may be one of the value is zero, that's why you are getting the error


There are three ways to avoid the "Division by zero encountered" error in your SELECT statement and these are as follows:

  • CASE statement
  • NULLIF/ISNULL functions
  • SET ARITHABORT OFF and SET ANSI_WARNINGS OFF

Using the CASE statement, your query will look like the following:

SELECT CASE WHEN [Denominator] = 0 THEN 0 ELSE [Numerator] / [Denominator] END AS [Percentage]
FROM [Table1]

If the denominator or divisor is 0, the result becomes 0. Otherwise, the division operation is performed.

Using the NULLIF and ISNULL functions, your query will look like the following:

SELECT ISNULL([Numerator] / NULLIF([Denominator], 0), 0) AS [Percentage]
FROM [Table1]

What this does is change the denominator into NULL if it is zero.  Then in the division, any number divided by NULL results into NULL.  So if the denominator is 0, then the result of the division will be NULL.  Then to return a value of 0 instead of a NULL value, the ISNULL function is used.


Lastly, using the SET ARITHABORT and SET ANSI_WARNINGS, your query will look like the following:

SET ARITHABORT OFF
SET ANSI_WARNINGS OFF

SELECT [Numerator] / [Denominator]

With both ARITHABORT and ANSI_WARNINGS set to OFF, SQL Server will return a NULL value in a calculation involving a divide-by-zero error.  To return a 0 value instead of a NULL value, you can put the division operation inside an ISNULL function:

SET ARITHABORT OFF
SET ANSI_WARNINGS OFF

SELECT ISNULL([Numerator] / [Denominator], 0)
  TSN ... replied to jason
04-Oct-11 11:28 PM
the problem when You are dividing either You are giving Null values in the denominator or you are diving the value with Zero...

Any ways the approach for avoiding this type of Error is ...

http://aartemiou.blogspot.com/2009/02/divide-by-zero-error-encountered.html

Well, as the error message says, whenever we have a division within a SQL query and the denominator has the value of zero (0) we get this error.

The exact error we get in SQL Server is:

Msg 8134, Level 16, State 1, Line [Here goes the line of the denominator in your query]
Divide by zero error encountered.


So, which is the best way of addressing this issue? As it is data-related we should be precautious anyway when having a division within a query and effectively control the denominator values for handling the case where a zero might be produced.

Just for reproducing the divide by zero error, consider the following example query:

declare @denominator int
set @denominator=0

select 1/@denominator


There are a few approaches of handling such problem. Here I present three.

Approach 1 - Using the "SET ANSI_WARNINGS OFF" Command
By using the "SET ANSI_WARNINGS OFF" command just right before the rest of the queries, it will allow your query that produces the error not to stop the execution of the rest of the queries.

Example:

SET ANSI_WARNINGS OFF

declare @denominator int

set @denominator=0

select 1/@denominator

.... Other queries go here


Approach 2 - Using the CASE Statement

By using the CASE statement it is possible to check the denominator value for a zero and if it is so you can use 1 in order for the division not to fail.

Example Query:

declare @denominator int
set @denominator=0

select 1/(case @denominator when 0 then 1 else @denominator end)


Alternatively, you can create a custom scalar-valued function that given an input parameter, it can check for a zero and if it is encountered it can return 1 else it should return the input:

CREATE FUNCTION check_denominator
(
-- Function parameter
@input int
)
RETURNS int
AS
BEGIN

-- Declare local variable
DECLARE @result int

-- Check for 0, if so then return 1 else return the input
SET @result =(SELECT (CASE @input when 0 then 1 else @input end))

-- Return the result
RETURN @result

END
GO


Then you can use the above function as follows:

declare @denominator int

set @denominator=0

select 1/dbo.check_denominator(@denominator)


Approach 3 - Using the NULLIF Function

Yep, by using the NULLIF function it is possible to handle the issue of a zero denominator.
But how? :)

The NULLIF function takes two arguments and if they have equal values it then returns a NULL.

The idea here is to compare the denominator value with a zero via NULLIF and if it returns a NULL then to handle it with the ISNULL function (by placing the number 1)!

Example:

declare @denominator int
set @denominator=0

select 1/ISNULL(NULLIF(@denominator,0),1)


hope this helps you....
 
  Web Star replied to jason
05-Oct-11 12:02 AM
Actually, you only need the NULLIF in denominator:

AVG(ISNULL(F.WinningBid/NULLIF(F.AuctionSellerReserve, 0), 0))

Try making a change similar to the above in your code.
  aneesa replied to jason
05-Oct-11 02:35 AM
PLEASE MODIFY THE QUERY WITH BELOW QUERY
UPDATE s
SET
s.mix_ty = CAST(s.net_sales_ty AS DECIMAL(19,5)) / NULLIF(CAST(b.net_sales_ty AS DECIMAL(19,5)),0),
s.mix_ly = CAST(s.net_sales_ly AS DECIMAL(19,5)) /NULLIF( CAST(b.net_sales_ly AS DECIMAL(19,5)),0)
FROM #sales s
INNER JOIN (
  SELECT division_code, SUM(net_sales_ty) AS net_sales_ty, SUM(net_sales_ly) AS net_sales_ly
  FROM #sales
  GROUP BY division_code
) b ON s.division_code = b.division_code



Divide by zero error encountered
The example below shows a workaround for a Divide by zero error encountered. error by using the NULLIF Function. NULLIF returns the first expression if the two expressions are not equivalent otherwise a NULL is returned.
 
Usage: SELECT NULLIF(col1, 0)
 
IF col1 = 0 then a NULL will be returned.
 
 
CREATE TABLE dbo.Products
  (
  Product VARCHAR(10),
  Price NUMERIC(7, 2),
  CostPrice NUMERIC(7, 2)
  )
 
 
INSERT dbo.Products SELECT 'Hammer', 12.00, 6.00
INSERT dbo.Products SELECT 'Nails',  0.10, 0.05
INSERT dbo.Products SELECT 'Screws', 0, 0.05
 
 
SELECT Product, (CostPrice / Price) * 100 AS PercentProfit FROM dbo.Products
 
Will Produce the following Error:
 
(3 row(s) affected)
 
Server: Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.
 
 
SELECT Product, (CostPrice / NULLIF(Price, 0))* 100 AS PercentProfit FROM dbo.Products
 
Returns:
 
Product    PercentProfit      
---------- -----------------------
Hammer   50.0000000000
Nails    50.0000000000
Screws   NULL
 
(3 row(s) affected)


  jason replied to jason
05-Oct-11 09:38 PM
Thankyou. Works great.
Create New Account
help
SQL Server Error: 18452 SQL Server Connection failed: SQLState: '28000' SQL Server Error: 18452 [Microsoft][ODBC SQL Server Driver][SQL Server] Login failed for user 'sa'. Reason: Not
Connectivity issue (SQL server error: 53 and 17) SQL Server SQL server 2000 standard edition, Microsoft Windows NT 5.2 (3790) One of my application running Microsoft access database connects to this server. Yesterday I applied a update to the application and now we are not able to
SQL Server Error 5520 SQL Server I am getting the SQL Server Error 5520 when i try to add a FILSTREAM file into a filegroup. I am trying
MSDE on Windows 2003 R2 box, new DL385G6 - Install Fails during SQL Services SQL Server I have been finding that I am having trouble with the Crystal Reports Server XI installation failing when it is dealing with SQL. So, as a thought and in case there was something wrong with my SQL portion of the isntall. I thought ok, I will try installing the actual MSDE application direct from Microsoft. So, I downloaded the MSDE for SQL 2000 (which is msde2000a.exe), set my switches and off to the races. It quit seconds left to the installation and bombed with the same errors as the Crystal Reports Server install. The error is the same whether I try to install MSDE by itself or
Additonal thoughts, you should be able to connect to SQL Server via SQL Server SQL Server Additonal thoughts, you should be able to connect to SQL Server via SQL Server Management Studio. This will provide you with whether or not SQL Server