Ошибка 8134 sql server

Here are five options for dealing with error Msg 8134 “Divide by zero error encountered” in SQL Server.

First, here’s an example of code that produces the error we’re talking about:

SELECT 1 / 0;

Result:

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

We get the error because we’re trying to divide a number by zero. Mathematically, this does not make any sense. You can’t divide a number by zero and expect a meaningful result.

To deal with this error, we need to decide what should be returned when we try to divide by zero. For example, we might want a null value to be returned. Or we might want zero to be returned. Or some other value.

Below are some options for dealing with this error.

Option 1: The NULLIF() Expression

A quick and easy way to deal with this error is to use the NULLIF() expression:

SELECT 1 / NULLIF( 0, 0 );

Result:

NULL

NULLIF() returns NULL if the two specified expressions are the same value. It returns the first expression if the two expressions are different. Therefore, if we use zero as the second expression, we will get a null value whenever the first expression is zero. Dividing a number by NULL results in NULL.

Actually, SQL Server already returns NULL on a divide-by-zero error, but in most cases we don’t see this, due to our ARITHABORT and ANSI_WARNINGS settings (more on this later).

Option 2: Add the ISNULL() Function

In some cases, you might prefer to return a value other than NULL.

In such cases, you can pass the previous example to the ISNULL() function:

SELECT ISNULL(1 / NULLIF( 0, 0 ), 0);

Result:

0

Here I specified that zero should be returned whenever the result is NULL.

Be careful though. In some cases, returning zero might be inappropriate. For example, if you’re dealing with inventory supplies, specifying zero might imply that there are zero products, which might not be the case.

Option 3: Use a CASE Statement

Another way to do it is to use a CASE statement:

DECLARE @n1 INT = 20;
DECLARE @n2 INT = 0;

SELECT CASE
    WHEN @n2 = 0
    THEN NULL
    ELSE @n1 / @n2
END

Result:

NULL

Option 4: The SET ARITHABORT Statement

The SET ARITHABORT statement ends a query when an overflow or divide-by-zero error occurs during query execution. We can use it in conjunction with SET ANSI WARNINGS to return NULL whenever the divide-by-zero error might occur:

SET ARITHABORT OFF;
SET ANSI_WARNINGS OFF;
SELECT 20 / 0;

Result:

NULL

Microsoft recommends that you always set ARITHABORT to ON in your logon sessions, and that setting it to OFF can negatively impact query optimisation, leading to performance issues.

Some clients (such as SQL Server Management Studio) set ARITHABORT to ON by default. This is why you probably don’t see the NULL value being returned when you divide by zero. You can use SET ARITHIGNORE to change this behaviour if you prefer.

Option 5: The SET ARITHIGNORE Statement

The SET ARITHIGNORE statement controls whether error messages are returned from overflow or divide-by-zero errors during a query:

SET ARITHABORT OFF;
SET ANSI_WARNINGS OFF;

SET ARITHIGNORE ON;
SELECT 1 / 0 AS Result_1;

SET ARITHIGNORE OFF;
SELECT 1 / 0 AS Result_2;

Result:

Commands completed successfully.
Commands completed successfully.
Commands completed successfully.
+------------+
| Result_1   |
|------------|
| NULL       |
+------------+
(1 row affected)
Commands completed successfully.
+------------+
| Result_2   |
|------------|
| NULL       |
+------------+
Division by zero occurred.

Here, I set ARITHABORT and ANSI_WARNINGS to OFF so that the statement wasn’t aborted due to the error, and NULL is returned whenever there’s a divide-by-zero error.

Note that the SET ARITHIGNORE setting only controls whether an error message is returned. SQL Server returns a NULL in a calculation involving an overflow or divide-by-zero error, regardless of this setting.

In the above example we can see that when ARITHIGNORE is ON, the division by zero error is not returned. When it’s OFF, the division by zero error message is returned.

Posted by Prashant on July 2, 2010

Problem:

While performing mathematical operations it throws Divided by zero error.

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

This situation often arises in production databases if the script has not been tested with sufficient data before putting the script to production database. This happens when a number is divided by 0 (zero).

Solution:

There can be many ways to handle this error. Here are some of my workarounds in SQL Server.

  1. Using NULLIF & ISNULL/ COALESCE
  2. Using CASE
  3. Using ARITHABORT & ANSI_WARNINGS

Method: 1

SELECT ISNULL(Number1 / NULLIF(Number2, 0), 0) AS [Result]
FROM tbl_err_8134

In this method uses NULLIF. In this case when the divisor is 0 (Zero) it will return NULL to the divisor, so the result will also became NULL. Then by IFNULL it returns 0 as the result is NULL here.

Method: 2

SELECT CASE WHEN Number2 = 0 THEN 0 ELSE Number1 / Number2 END AS [Result]
FROM tbl_err_8134

In this method uses CASE. Here when the divisor is 0 (Zero) it will return 0 as result or else the result will be division of two numbers.

Method: 3

SET ARITHABORT OFF
SET ANSI_WARNINGS OFF
GO

SELECT ISNULL(Number1 / Number2, 0) AS [Result]
from tbl_err_8134

Here when ARITHABORT & ANSI_WARNINGS are set to OFF it will continue processing and will return NULL as a result. To know more about ARITHABORT you can follow this link.

Download the complete script file here.

This entry was posted on July 2, 2010 at 5:45 PM and is filed under Interview Questions, SQL Server.
Tagged: arithabort, divide by zero, Functions, Prashant Pattnaik, SQL Journey, SQL Server, Technology. You can follow any responses to this entry through the RSS 2.0 feed.

You can leave a response, or trackback from your own site.

Stuck with ‘SQL server divide by zero error encountered’? We can help you.

Recently, one of our customer came across this error as it is not possible to divide a number by zero. It leads to infinity. We perform data calculations in SQL Server for various considerations.

As part of your Server Management Services, we assist our customers with several SQL queries.

Today, let us see how to fix this error.

Cause for the error ‘SQL Server divide by zero error encountered’

Let us see what could cause the error ‘SQL Server divide by zero error encountered’.

To start with, If the product2 quantity goes out of stock and that means we do not have any quantity for product2.

DECLARE @Product1 INT;
DECLARE @Product2 INT;
SET @Product1 = 50;
SET @Product2 = 0;
SELECT @Product1 / @Product2 ProductRatio;

We get SQL divide by zero error messages (message id 8134, level 16):

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

How to solve the error ‘SQL Server divide by zero error encountered’?

Always, it is a best practice to write code in such a way that it does not give divide by zero message. It should have a mechanism to deal proactively with such conditions.

Moving ahead, let us see an effective methods followed by our Support Techs employ in order to solve this error.

Method 1: SQL NULLIF Function

Initially, we use NULLIF function to avoid divide by zero error message.

The syntax of NULLIF function:

NULLIF(expression1, expression2)

It accepts two arguments.

  • Firstly, If both the arguments are equal, it returns a null value

For example, suppose that the value of both arguments is 10.

SELECT NULLIF(10, 10) result;

In this case, the output will be null.

  •  Secondly, If both the arguments are not equal, it returns the value of the first argument.

In this example, both argument values differ. It returns the output as value of first argument 10.

SELECT NULLIF(10, 5) result;

We can modify our initial query using the SQL NULLIF statement. We place the following logic using NULLIF function for eliminating SQL divide by zero error:

  • Use NULLIF function in the denominator with second argument value zero
  • If the value of the first argument is also zero, this function returns a null value. In SQL Server, if we divide a number with null, the output is null as well.
  • If the value of the first argument is not zero, it returns the first argument value and division takes place as standard values.
DECLARE @Product1 INT;
DECLARE @Product2 INT;
SET @Product1 = 50;
SET @Product2 = 0;
SELECT @Product1 / NULLIF(@Product2,0) ProductRatio;

Execute this modified query. We will get the output as NULL because denominator contains value zero.

If we do not want null value in the output, we can use SQL ISNULL function to avoid null values in the output and display a definite value. This function replaces the null value in the expression1 and returns expression2 value as output.

Method 2: Using CASE statement to avoid divide by zero error

Secondly, you can use a CASE statement in SQL to return values based on specific conditions. The Case statement checks for the value of @Product2 parameter:

  •  If the @Product2 value is zero, it returns null.
  • If the above condition is not satisfied, it does the arithmetic operation (@Product1/@Product2) and returns the output.
DECLARE @Product1 INT;
DECLARE @Product2 INT;
SET @Product1 = 50;
SET @Product2 = 0;
SELECT CASE
WHEN @Product2 = 0
THEN NULL
ELSE @Product1 / @Product2
END AS ProductRatio;

We will get output as NULL.

Method 3: SET ARITHABORT OFF

By default, SQL Server has a default value of SET ARITHABORT is ON. We get SQL divide by zero error in the output using the default behavior.

The T-SQL syntax for controlling the ARITHABORT option is shown below:

SET ARITHABORT { ON | OFF }

  •  Using ARITHABORT ON, the query will terminate with divide by zero message. It is the default behavior.
SET ARITHABORT ON — Default
SET ANSI_WARNINGS ON
DECLARE @Product1 INT;
DECLARE @Product2 INT;
SET @Product1 = 50;
SET @Product2 = 0;
SELECT @Product1 / @Product2 ProductRatio;

We get the SQL divide by zero error messages.

  • Using ARITHABORT OFF, the batch will terminate and returns a null value. We need to use ARITHABORT in combination with SET ANSI_WARNINGS OFF to avoid the error message:
SET ARITHABORT OFF
SET ANSI_WARNINGS OFF
DECLARE @Product1 INT;
DECLARE @Product2 INT;
SET @Product1 = 50;
SET @Product2 = 0;
SELECT @Product1 / @Product2 ProductRatio;

We will get the output as NULL.

Finally, you can use the following query to check the current setting for the ARITHABORT parameter:

DECLARE @ARITHABORT VARCHAR(3) = ‘OFF’;
IF ( (64 & @@OPTIONS) = 64 ) SET @ARITHABORT = ‘ON’;
SELECT @ARITHABORT AS ARITHABORT;

The default ARITHABORT setting for SQL Server Management Studio (SSMS) is ON. We can view it using SSMS Tools properties. Navigate to Tools -> Options -> Advanced.

We should not modify the value of ARITHABORT unless required. It might create performance issues, as well. It is better to use other methods for avoiding SQL divide by zero error.

[Need assistance? We can help you]

Conclusion

In short, we saw how our Support Techs resolve error ‘SQL Server divide by zero error encountered’

Are you using Docker based apps?

There are proven ways to get even more out of your Docker containers! Let us help you.

Spend your time in growing business and we will take care of Docker Infrastructure for you.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Home > SQL Server Error Messages > Msg 8134 — Divide by zero error encountered

SQL Server Error Messages — Msg 8134 — Divide by zero error encountered

SQL Server Error Messages — Msg 8134

Error Message

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

Causes:

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.

Solution / Work Around:

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)
Related Articles :
  • Frequently Asked Questions — SQL Server Error Messages
  • Frequently Asked Questions — INSERT Statement
  • Frequently Asked Questions — SELECT Statement

Problem

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

While performing division operation in SQL Server, you may come across this error when you try to divide a number by 0.

Msg 8134 Divide by zero error encountered

To avoid this error, you can check and make sure that the divisor is not 0. Another option is to catch the exception in the proper way and throw the message to the front end, so as you can easily identify what went wrong and where the exception happened. Let us see both the options.

Option 1: Check for 0 and make it NULL

This is kind of suppressing the exception. Using the NULLIF function, check the divisor for 0 and change it to NULL. A number when divided by NULL will become NULL. So, there will not be any exception and the result of the division operation is NULL.

DECLARE @variable1 FLOAT,
	@variable2 FLOAT;

SELECT @variable1 = 100,
	@variable2 = 0;

SELECT @variable1 / NULLIF(@variable2, 0) Result;

Check for 0 and make it NULL

Option 2: Handle the exception

This option of handling the exception will be helpful when you are performing mathematical operations in a stored procedure. When there are several mathematical operations, catching and throwing the exception outside the stored procedure will be greatly helpful to debug and figure out the problem. Let’s see an example.

Here is a stored procedure with a division operation and exception handling. This procedure has two output parameters, one to get the result and another to get the error message.

/** Create Stored procedure **/
CREATE PROCEDURE mtb_DivisionOperation
	@Value1 FLOAT,
	@Value2 FLOAT,
	@Result FLOAT OUTPUT,
	@Error NVARCHAR(MAX) OUTPUT
AS
BEGIN
	BEGIN TRY

        SET @Result = @Value1 / @Value2;

    END TRY
    BEGIN CATCH
        SET @Error = 'Error Number: ' + CAST(ERROR_NUMBER() AS VARCHAR(10)) + '; ' + Char(10) +
        'Error Severity: ' + CAST(ERROR_SEVERITY() AS VARCHAR(10)) + '; ' + Char(10) +
        'Error State: ' + CAST(ERROR_STATE() AS VARCHAR(10)) + '; ' + Char(10) +
        'Error Line: ' + CAST(ERROR_LINE() AS VARCHAR(10)) + '; ' + Char(10) +
        'Error Message: ' + ERROR_MESSAGE()
    END CATCH
END
GO

When there divisor is 0, then the @Result output parameter will be NULL and the @ErrorMsg output parameter will have the error details.

/** Execute Stored Procedure **/
DECLARE @ResultVal FLOAT
DECLARE @ErrorMsg NVARCHAR(MAX)

EXEC mtb_DivisionOperation 
	@Value1 = 100, @Value2 = 0,  
	@Result = @ResultVal OUTPUT, @Error = @ErrorMsg OUTPUT

SELECT @ResultVal AS 'Result'
SELECT @ErrorMsg AS 'Error Message'
GO

/** Results **/

Result
----------------------
NULL

(1 row affected)

Error Message
----------------------
Error Number: 8134; 
Error Severity: 16; 
Error State: 1; 
Error Line: 11; 
Error Message: Divide by zero error encountered.

(1 row affected)

Handle the exception

When the divisor is not 0, the @Result output parameter will have a value and the @ErrorMsg output parameter will be NULL.

/** Execute Stored Procedure **/
DECLARE @ResultVal FLOAT
DECLARE @ErrorMsg NVARCHAR(MAX)

EXEC mtb_DivisionOperation 
	@Value1 = 100, @Value2 = 3,  
	@Result = @ResultVal OUTPUT, @Error = @ErrorMsg OUTPUT

SELECT @ResultVal AS 'Result'
SELECT @ErrorMsg AS 'Error Message'
GO

/** Results **/

Result
----------------------
33.3333333333333

(1 row affected)

Error Message
----------------------
NULL

(1 row affected)

Reference

  • About TRY-CATCH blocks in T-SQL at Microsoft Docs.

Понравилась статья? Поделить с друзьями:
  • Ошибка 8314 шкода октавия
  • Ошибка 813 на виндовс 10
  • Ошибка 813 летай
  • Ошибка 831 микас 11
  • Ошибка 8120 хонда