Ошибка арифметического переполнения при преобразовании expression к типу данных int sql

Устранена проблема, из-за которой вы получаете сообщение об ошибке "MSG 8115", а также "Ошибка арифметического переполнения при преобразовании выражения в тип данных int" при запуске системной хранимой процедуры sp_tables_info_90_rowset_64. Эта проблема возникает на связанном сервере SQL Server 2012.

SQL Server 2012 Developer SQL Server 2012 Enterprise SQL Server 2012 Standard Еще…Меньше

Проблемы

Рассмотрим следующий сценарий.

  • Вы создаете связанный сервер для Microsoft SQL Server 2012.

  • При попытке выполнить инструкцию SQL, вызывающую системную хранимую процедуру sys.sp_tables_info_90_rowset_64 , чтобы получить доступ к таблице из экземпляра SQL Server 2012 по умолчанию.

  • Таблица содержит более 2 500 000 000 записей.

В этом случае появляется следующее сообщение об ошибке:

Сообщение 8115, уровень 16, состояние 2, sp_tables_info_90_rowset_64 процедуры, строка 9Arithmetic ошибка переполнения при преобразовании выражения в тип данных int.

Примечание.Эта проблема возникает при настройке SQL Server 2012 в качестве целевого сервера.

Решение

Сведения о накопительном пакете обновления

Накопительный пакет обновления 1 (SP1) для SQL Server 2012 с пакетом обновления 1 (SP1)

Исправление для этой проблемы впервые выпущено в накопительном обновлении 1. За дополнительными сведениями о том, как получить этот накопительный пакет обновления для SQL Server 2012 с пакетом обновления 1 (SP1), щелкните следующий номер статьи базы знаний Майкрософт:

2765331 Накопительный пакет обновления 1 (SP1) для SQL Server 2012 с пакетом обновления 1 (SP1)Примечание. Так как сборки являются кумулятивными, каждый новый выпуск исправлений содержит все исправления и все исправления безопасности, которые были включены в предыдущий выпуск исправлений для SQL Server 2012. Рекомендуется установить последнюю версию исправления, которая включает это исправление. Дополнительные сведения см. в следующей статье базы знаний Майкрософт:

2772858 Сборки SQL Server 2012, выпущенные после выпуска пакета обновления 1 (SP1) для SQL Server 2012

SQL Server 2012

Исправление для этой проблемы впервые выпущено в накопительном обновлении 4. Для получения дополнительных сведений о том, как получить этот накопительный пакет обновления для SQL Server 2012, щелкните следующий номер статьи базы знаний Майкрософт:

2758687 Накопительный пакет обновления 4 для SQL Server 2012Примечание. Так как сборки являются кумулятивными, каждый новый выпуск исправлений содержит все исправления и все исправления безопасности, которые были включены в предыдущий выпуск исправлений для SQL Server 2012. Рекомендуется установить последнюю версию исправления, которая включает это исправление. Дополнительные сведения см. в следующей статье базы знаний Майкрософт:

2692828 Сборки SQL Server 2012, выпущенные после выпуска SQL Server 2012

Статус

Корпорация Майкрософт подтверждает наличие этой проблемы в своих продуктах, которые перечислены в разделе «Применяется к».

Дополнительная информация

Дополнительные сведения о том, как настроить связанные серверы в SQL Server 2012, можно найти на веб-сайте MSDN по следующему адресу:

Настройка связанных серверов в SQL Server 2012

Нужна дополнительная помощь?

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.

  • 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

  • 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

Понравилась статья? Поделить с друзьями:
  • Ошибка аср камаз
  • Ошибка арифметического переполнения при преобразовании expression к типу данных datetime
  • Ошибка архикад невозможно создать временные документы
  • Ошибка аристон sp1 на котле что значит
  • Ошибка архивации хранилище теневой копии 0x80780038