Ошибка arithmetic overflow error converting expression to data type int

If you’re receiving error Msg 8115, Level 16, Arithmetic overflow error converting expression to data type int in SQL Server, it could be that you’re performing a calculation that results in an out of range value.

If you’re receiving error Msg 8115, Level 16, Arithmetic overflow error converting expression to data type int in SQL Server, it could be that you’re performing a calculation that results in an out of range value.

This can happen when you use a function such as SUM() on a column, and the calculation results in a value that’s outside the range of the column’s type.

Example of the Error

Here’s an example of code that produces the error:

SELECT SUM(bank_balance) 
FROM accounts;

Result:

Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type int.

In this case I used the SUM() function to get the sum of the bank_balance column, which has a data type of int.

The error occurred because the result of the calculation is outside the range of the int data type.

Here’s all the data in my table:

SELECT bank_balance 
FROM accounts;

Result:

+----------------+
| bank_balance   |
|----------------|
| 1300000000     |
| 1200000000     |
| 800500000      |
+----------------+

Those are some big bank balances… and adding the three of them results in a larger number than an int can handle (the int range is -2,147,483,648 to 2,147,483,647).

The Solution

We can deal with this error by converting the int column to a bigint when we run the query:

SELECT SUM(CAST(bank_balance AS bigint)) 
FROM Accounts;

Result:

3300500000

This time it worked.

You could also change the data type of the actual column for a more permanent solution.

In case you’re wondering, the bigint range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

Same Error in Different Scenarios

The same error (Msg 8115) can also occur (with a slightly different error message) when you try to explicitly convert between data types and the original value is outside the range of the new type. See Fix “Arithmetic overflow error converting int to data type numeric” in SQL Server to fix this.

The same error (Msg 8115) can also occur (with a slightly different error message) when you try to insert data into a table when its IDENTITY column has reached its data type’s limit. See Fix: “Arithmetic overflow error converting IDENTITY to data type…” in SQL Server for how to fix this.

With SQL Server, how to avoid this error : “Arithmetic overflow error converting expression to data type int”. Let’s insert some data into a table using a stored procedure for example. Facing this SQL Server error message can be disturbing. Even if SQL conversion errors are classical ones, finding the solution and apply the industry best practices to avoid them is very useful.

In this case, the stored procedure executing the query generates some dynamic T-SQL code. Then it executes the code and insert data from various tables into one single target table. It’s a typical SQL Server int arithmetic overflow conversion error.

How to avoid the SQL Server Arithmetic overflow error?

While running the same piece of T-SQL code independently, that is outside the stored procedure, directly into the SQL Server Management Studio windows, no error is faced. But when integrating the same code into the stored procedure, this error is thrown:

Msg 50000, Level 16, State 2, Procedure MyStoredProcedure, Line 123
Arithmetic overflow error converting expression to data type int.

After analysis, the conversion error message didn’t come from the SELECT clause. The SQL INSERT clause from the same T-SQL stored procedure is throwing the error. The root cause is the the insertion of a big integer value into the table. For integer Data Type in SQL Server, the number must be between -2^31 (-2 to the power of 31) and 2^31 (2 to the power of 31).

Namely the range for the INTEGER type is exactly between -2,147,483,648 and 2,147,483,648.

Use another data type to avoid the conversion error

The solution to avoid Arithmetic overflow error converting expression is to use a bigger data type. The solution to avoid this arithmetic overflow error is to change the data type from INT to BIGINT or DECIMAL(11,0) for example.

Please note that in this case the conversion error is because the integer number is too big. It can also be an insertion of a text value into an integer field. Check out the int, bigint, smallintand tinyint official documentation for SQL Server.

Other classical conversion questions

This article shows how to simply avoid an Arithmetic overflow error converting expression to int in SQL Server. It happens when inserting a bigger number in an integer data type. Check out more classical SQL Server errors like the insert of a duplicate key.

What is a SQL Server arithmetic overflow error?

An arithmetic overflow error is an error faced when converting from one SQL Server data type to another one. For example from a numeric figure to an integer because the integer type can handle smaller figures compared to the numeric type.

What’s the biggest number for a SQL Server INTEGER?

The biggest number for the SQL Server integer data type is from -2 to the power of 31 till 2 to the power of 31. It means from -2^31 to 2^31 which is exactly this range: from -2,147,483,648 to 2,147,483,648. To avoid conversion error, always consider the maximum value for the data and size the database and the data types accordingly.

What’s the difference between INT and BIGINT?

A bigint is an integer, i.e. a number without decimals, and in SQL Server it can go from -2^63 that is exactly -9,223,372,036,854,775,808 to 2^63-1 which is 9,223,372,036,854,775,807 and is using 8 Bytes in storage.
While an INTEGER is from -2^31 which equals -2,147,483,648 to 2^31-1 which is exactly 2,147,483,647. An INTEGER data is stored on 4 Bytes.

How to avoid conversion errors with SQL Server?

One good practice to avoid conversion errors during is to put in place controls for the inputs. And moreover make sure to control the values inserted in the database. For example, users can only enter valid dates in a date field.

Check out how to manage time difference in hours minutes and also seconds with T-SQL.

  • Remove From My Forums
  • Question

  • I cant seem to get past the erro «Arithmetic overflow error converting expression to data type int.«

    My code is

    CONVERT(BigInt,(SUM(CASE WHEN col1 > 100000000 THEN 1 ELSE 0 END)))/CONVERT(Bigint,(SUM(CASE WHEN col1 > 10000000 THEN 1 ELSe 0 end)))*2 As ‘LargeSpend’

    Could anyone advise please?

    Thanks

Answers

  • Hi there,

    I suggest you to use CAST instead of CONVERT. I tried this conversion with CAST and it worked successfully (see below):

    USE [tempdb]
    GO
    CREATE TABLE #MyTable (col1 bigint)
    INSERT INTO #MyTable VALUES ('10000000003')
    INSERT INTO #MyTable VALUES ('20000000004')
    INSERT INTO #MyTable VALUES ('30000000003')
    SELECT CAST((SUM(CASE WHEN col1 > 100000000 THEN 1 ELSE 0 END)) AS [bigint])
    /CAST((SUM(CASE WHEN col1 > 10000000 THEN 1 ELSe 0 end)) AS [bigint])*2 AS 'LargeSpend'
    FROM #MyTable


    Regards,

    Basit A. Farooq (MSC Computing, MCITP SQL Server 2005 & 2008, MCDBA SQL Server 2000)

    http://basitaalishan.com

    Please remember to click «Mark as Answer» on the post that helps you, and to click
    «Unmark as Answer» if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

    • Proposed as answer by

      Friday, August 17, 2012 1:45 PM

    • Marked as answer by
      Iric Wen
      Monday, August 27, 2012 9:16 AM

  • Remove From My Forums
  • Question

  • Hi,

    When I execute the below stored procedure I get the error that «Arithmetic overflow error converting expression to data type int». I am not sure how to fix this? Any ideas? TIA

    USE [FileSharing]
    GO
    /****** Object:  StoredProcedure [dbo].[xlaAFSsp_reports]    Script Date: 24.07.2015 17:04:10 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    
    
    ALTER PROCEDURE [dbo].[xlaAFSsp_reports]
     AS
    
    SET NOCOUNT ON
    -- Consolidate disk size (also done on xlaAFSsp_expire_files)
    update xlaAFSstorages set currentsize=isnull((select SUM(filesize) from xlaAFSfiles where s3=0 and storageid=xlaAFSstorages.storageid),0)
    
    create table #ttable (
    totalfiles int,
    usedspace int,
    nonexpiring int,
    protected int,
    totalusers int,
    paidusers int,
    totalstorages int,
    allocatedspace int,
    )
    
    -- Total Stats
    insert into #ttable (totalfiles,usedspace,nonexpiring,protected,totalusers,paidusers,totalstorages,allocatedspace) values (0,0,0,0,0,0,0,0)
    update #ttable set totalfiles=(Select count(fileid) from xlaAFSfiles), 
    usedspace=(Select isnull(sum(filesize),0) from xlaAFSfiles), 
    nonexpiring=(Select count(fileid) from xlaAFSfiles where fsid in (select fsid from xlaAFSfilesets where expiredate='-')), 
    protected=(Select count(fileid) from xlaAFSfiles where fsid in (select fsid from xlaAFSfilesets where accesspwd<>'')),
    totalusers=(Select COUNT(userid) from xlaAFSusers),
    paidusers=(Select COUNT(userid) from xlaAFSusers where ispaid<>''),
    totalstorages=(Select COUNT(storageid) from xlaAFSstorages),
    allocatedspace=(Select isnull(SUM(allocatedsize),-1) from xlaAFSstorages)
    
    
    select * from #ttable
    drop table #ttable

    USE [FileSharing]
    GO
    
    DECLARE	@return_value int
    
    EXEC	@return_value = [dbo].[xlaAFSsp_reports]
    
    SELECT	'Return Value' = @return_value
    
    GO

    Msg 8115, Level 16, State 2, Procedure xlaAFSsp_reports, Line 25

    Arithmetic overflow error converting expression to data type int.

    The statement has been terminated.

    (1 row(s) affected)

Answers

  • Instead of INT use BIGINT in all your tables. It may very well be that SUM(TotalSize) exceeds max for the INT.


    • Marked as answer by

      Friday, July 24, 2015 5:26 PM

  • Why you can not modify the table definition if it’s a temporary table? Sure you can.

    Are you saying this procedure is used to insert into another permanent table? If so, you would not be able to fit bigint into int column.

    So, there are 2 solutions:

    1. Change structure of your tables to use BigInt instead of Int.

    2. Use case expressions, e.g.

    case when cast(sum(column) as BigInt) > 2,147,483,647 then NULL else

    sum(column) end

    —————-

    You will know that NULL means the total size is too big for the integer column to hold.


    • Marked as answer by
      GibsonLP2012
      Friday, July 24, 2015 5:26 PM

  • Thank you I corrected the issue adjusted the cast/sum order:

    =(Selectisnull(sum(cast(filesize
    asbigint)),0)fromxlaAFSfiles)

    • Marked as answer by
      GibsonLP2012
      Friday, July 24, 2015 5:26 PM

  • Just update the table definition on the temp table you are creating:

    create table #ttable (
    totalfiles int,
    usedspace BIGINT, -- OR Match FilleSIze  datatype to avoid additional conversions
    nonexpiring int,
    protected int,
    totalusers int,
    paidusers int,
    totalstorages int,
    allocatedspace int,
    )

    Casting on the sum will only be needed if SQL Server has problems converting from whatever type Filesize is to an int. If FileSize field is an int then as Naomi points out the sum of all files exceeds the maximum value for an int datatype and you need to
    update your table defintion to BIGINT. (as shown above) If filesize is a float/ decimal/ bigint datatype just match the datetype on your temp table defintion to avoid additional casting/conversions.

    Hope that helps

    • Marked as answer by
      GibsonLP2012
      Friday, July 24, 2015 7:16 PM

Problem

DMS-E-GENERAL, a general exception error has occurred during operation attach database
arithmetic overflow error converting expression to datatype int.
DMS-E-GENERAL, a general exception error has occurred during operation attach database
General SQL server error: Check messages from the SQL Server.

Resolving The Problem

This will occur if you are using an expression to convert a value into an integer and somewhere in the column there is an invalid digit, such as a letter or symbol.

The expression may not necessarily be in the report, although it is the first place to look. It could be in a view that the report calls upon. In this case, the error may be from the SQL in that view. In either cases, it is recommended to resolve the data problem in the database by doing a report against the column that you are converting and filter out only the numeric values 0,1,2,3,4,5,6,7,8,9 and see what you are left with. Also, check the SQL Server log for more
info.

[{«Product»:{«code»:»SSTQPQ»,»label»:»IBM Cognos Series 7 PowerPlay»},»Business Unit»:{«code»:»BU053″,»label»:»Cloud & Data Platform»},»Component»:»Impromptu»,»Platform»:[{«code»:»PF025″,»label»:»Platform Independent»}],»Version»:»Impromptu 5.0″,»Edition»:»»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»}}]

Microsoft distributes Microsoft SQL Server 2008 fixes as one downloadable file. Because the fixes are cumulative, each new release contains all the hotfixes and all the security fixes that were included with the previous SQL Server 2008 fix release.

Symptoms

Consider the following scenario.

  • You enable the data collector.

  • Under a heavy or prolonged workload, when the data collector runs, database maintenance activity on very large databases, such as rebuilding indexes, and updating statistics, may lead to the arithmetic overflow error as follows. This arithmetic overflow error occurs intermittently during the Collect a snapshot of sys.dm_exec_query_stats phase.

Message: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E57.
An OLE DB record is available. Source: «Microsoft SQL Server Native Client 10.0» Hresult: 0x80040E57 Description: «Arithmetic overflow error converting expression to data type int.».


If you increase the data collector logging level to 2 (for example, you run the «exec sp_syscollector_update_collection_set @collection_set_id=<CollectionSetID>,@logging_level = 2» statement), the following error messages are returned:

<Date Time>,SEQ — Capture and analyze query statistics and query plan and text,Error,6569,,,,SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E57.<nl/>An OLE DB record is available. Source: «Microsoft SQL Server Native Client 10.0» Hresult: 0x80040E57 Description: «Arithmetic overflow error converting expression to data type int.».,, <Date Time>,,<Date Time>,,,,OnError,-1071636471 <Date Time>,QueryActivityUpload,Error,6569,,,,SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E57.<nl/>An OLE DB record is available. Source: «Microsoft SQL Server Native Client 10.0» Hresult: 0x80040E57 Description: «Arithmetic overflow error converting expression to data type int.».,, <Date Time>,,<Date Time>,,,,OnError,-1071636471

<Date Time>,DFT — Create Interesting Queries Upload Batch,Error,6569,,,,component «ODS — Get current snapshot of dm_exec_query_stats» (16412) failed the pre-execute phase and returned error code 0xC0202009.,, <Date Time>,,<Date Time>,,,,OnError,-1073450982

<Date Time>,SEQ — Capture and analyze query statistics and query plan and text,Error,6569,,,,component «ODS — Get current snapshot of dm_exec_query_stats» (16412) failed the pre-execute phase and returned error code 0xC0202009.,, <Date Time>,,<Date Time>,,,,OnError,-1073450982

<Date Time>,QueryActivityUpload,Error,6569,,,,component «ODS — Get current snapshot of dm_exec_query_stats» (16412) failed the pre-execute phase and returned error code 0xC0202009.,, <Date Time>,,<Date Time>,,,,OnError,-1073450982

In this scenario, the following statement that is run by SQL Server causes the arithmetic overflow error:

SET NOCOUNT ON
DECLARE @p1 datetime
SET @p1 = GETDATE()

SELECT
[sql_handle],
statement_start_offset,
statement_end_offset,
-- Use ISNULL here and in other columns to handle in-progress queries that are not yet in sys.dm_exec_query_stats.
-- These values only come from sys.dm_exec_query_stats. If the plan does not show up in sys.dm_exec_query_stats
-- (first execution of a still-in-progress query, visible in sys.dm_exec_requests), these values will be NULL.
MAX (plan_generation_num) AS plan_generation_num,
plan_handle,
MIN (creation_time) AS creation_time,
MAX (last_execution_time) AS last_execution_time,
SUM (execution_count) AS execution_count,
SUM (total_worker_time) AS total_worker_time,
MIN (min_worker_time) AS min_worker_time, -- NULLable
MAX (max_worker_time) AS max_worker_time,
SUM (total_physical_reads) AS total_physical_reads,
MIN (min_physical_reads) AS min_physical_reads, -- NULLable
MAX (max_physical_reads) AS max_physical_reads,
SUM (total_logical_writes) AS total_logical_writes,
MIN (min_logical_writes) AS min_logical_writes, -- NULLable
MAX (max_logical_writes) AS max_logical_writes,
SUM (total_logical_reads) AS total_logical_reads,
MIN (min_logical_reads) AS min_logical_reads, -- NULLable
MAX (max_logical_reads) AS max_logical_reads,
SUM (total_clr_time) AS total_clr_time,
MIN (min_clr_time) AS min_clr_time, -- NULLable
MAX (max_clr_time) AS max_clr_time,
SUM (total_elapsed_time) AS total_elapsed_time,
MIN (min_elapsed_time) AS min_elapsed_time, -- NULLable
MAX (max_elapsed_time) AS max_elapsed_time,
@p1 AS collection_time
FROM
(
SELECT
[sql_handle],
statement_start_offset,
statement_end_offset,
plan_generation_num,
plan_handle,
creation_time,
last_execution_time,
execution_count,
total_worker_time,
min_worker_time,
max_worker_time,
total_physical_reads,
min_physical_reads,
max_physical_reads,
total_logical_writes,
min_logical_writes,
max_logical_writes,
total_logical_reads,
min_logical_reads,
max_logical_reads,
total_clr_time,
min_clr_time,
max_clr_time,
total_elapsed_time,
min_elapsed_time,
max_elapsed_time
FROM sys.dm_exec_query_stats AS q
-- Temporary workaround for VSTS #91422. This should be removed if/when sys.dm_exec_query_stats reflects in-progress queries.
UNION ALL
SELECT
r.[sql_handle],
r.statement_start_offset,
r.statement_end_offset,
ISNULL (qs.plan_generation_num, 0) AS plan_generation_num,
r.plan_handle,
ISNULL (qs.creation_time, r.start_time) AS creation_time,
r.start_time AS last_execution_time,
1 AS execution_count,
-- dm_exec_requests shows CPU time as ms, while dm_exec_query_stats
-- uses microseconds. Convert ms to us.
r.cpu_time * 1000 AS total_worker_time,
qs.min_worker_time, -- min should not be influenced by in-progress queries
r.cpu_time * 1000 AS max_worker_time,
r.reads AS total_physical_reads,
qs.min_physical_reads, -- min should not be influenced by in-progress queries
r.reads AS max_physical_reads,
r.writes AS total_logical_writes,
qs.min_logical_writes, -- min should not be influenced by in-progress queries
r.writes AS max_logical_writes,
r.logical_reads AS total_logical_reads,
qs.min_logical_reads, -- min should not be influenced by in-progress queries
r.logical_reads AS max_logical_reads,
qs.total_clr_time, -- CLR time is not available in dm_exec_requests
qs.min_clr_time, -- CLR time is not available in dm_exec_requests
qs.max_clr_time, -- CLR time is not available in dm_exec_requests
-- dm_exec_requests shows elapsed time as ms, while dm_exec_query_stats
-- uses microseconds. Convert ms to us.
r.total_elapsed_time * 1000 AS total_elapsed_time,
qs.min_elapsed_time, -- min should not be influenced by in-progress queries
r.total_elapsed_time * 1000 AS max_elapsed_time
FROM sys.dm_exec_requests AS r
LEFT OUTER JOIN sys.dm_exec_query_stats AS qs ON r.plan_handle = qs.plan_handle AND r.statement_start_offset = qs.statement_start_offset
AND r.statement_end_offset = qs.statement_end_offset
WHERE r.sql_handle IS NOT NULL
) AS query_stats
OUTER APPLY sys.dm_exec_sql_text (sql_handle) AS sql
GROUP BY [sql_handle], plan_handle, statement_start_offset, statement_end_offset
ORDER BY [sql_handle], plan_handle, statement_start_offset, statement_end_offset

Therefore, if you manually run this statement, you may also receive the following error message:

Msg 8115, Level 16, State 2,

Arithmetic overflow error converting expression to data type int

Resolution


The fix for this issue was first released in Cumulative Update 5 for SQL Server 2008 Service Pack 1. For more information about this cumulative update package, click the following article number to view the article in the Microsoft Knowledge Base:

975977 Cumulative update package 5 for SQL Server 2008 Service Pack 1Note Because the builds are cumulative, each new fix release contains all the hotfixes and all the security fixes that were included with the previous SQL Server 2008 fix release. Microsoft recommends that you consider applying the most recent fix release that contains this hotfix. For more information, click the following article number to view the article in the Microsoft Knowledge Base:

970365 The SQL Server 2008 builds that were released after SQL Server 2008 Service Pack 1 was released
Microsoft SQL Server 2008 hotfixes are created for specific SQL Server service packs. You must apply a SQL Server 2008 Service Pack 1 hotfix to an installation of SQL Server 2008 Service Pack 1. By default, any hotfix that is provided in a SQL Server service pack is included in the next SQL Server service pack.

Status

Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the «Applies to» section.

References

For more information about the Incremental Servicing Model for SQL Server, click the following article number to view the article in the Microsoft Knowledge Base:

935897 An Incremental Servicing Model is available from the SQL Server team to deliver hotfixes for reported problems

For more information about the naming schema for SQL Server updates, click the following article number to view the article in the Microsoft Knowledge Base:

822499New naming schema for Microsoft SQL Server software update packages

For more information about software update terminology, click the following article number to view the article in the Microsoft Knowledge Base:

824684 Description of the standard terminology that is used to describe Microsoft software updates

Понравилась статья? Поделить с друзьями:
  • Ошибка argument not optional vba
  • Ошибка archpr выбранный файл не является zip rar ace arj архивом
  • Ошибка application load error 5 0000065434 гта вай сити
  • Ошибка application has stopped working world of tanks windows 7
  • Ошибка application has stopped working a problem occurred during the world of tanks