I’m getting this error
msg 8115, level 16, state 2, line 18
Arithmetic overflow error converting expression to data type int.
with this SQL query
DECLARE @year VARCHAR(4);
DECLARE @month VARCHAR(2);
-- START OF CONFIGURATION SECTION
-- THIS IS THE ONLY SECTION THAT SHOULD BE MODIFIED
-- SET THE YEAR AND MONTH PARAMETERS
SET @year = '2013';
SET @month = '3'; -- 1 = January.... 12 = Decemeber.
-- END OF CONFIGURATION SECTION
DECLARE @startDate DATE
DECLARE @endDate DATE
SET @startDate = @year + '-' + @month + '-01 00:00:00';
SET @endDate = DATEADD(MONTH, 1, @startDate);
SELECT
DATEPART(YEAR, dateTimeStamp) AS [Year]
, DATEPART(MONTH, dateTimeStamp) AS [Month]
, COUNT(*) AS NumStreams
, [platform] AS [Platform]
, deliverableName AS [Deliverable Name]
, SUM(billableDuration) AS NumSecondsDelivered
FROM
DeliveryTransactions
WHERE
dateTimeStamp >= @startDate
AND dateTimeStamp < @endDate
GROUP BY
DATEPART(YEAR, dateTimeStamp)
, DATEPART(MONTH, dateTimeStamp)
, [platform]
, deliverableName
ORDER BY
[platform]
, DATEPART(YEAR, dateTimeStamp)
, DATEPART(MONTH, dateTimeStamp)
, deliverableName
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.
When I run this command with SUM()
SELECT COUNT(*) AS [Records], SUM(t.Amount) AS [Total]
FROM dbo.t1 AS t
WHERE t.Id > 0
AND t.Id < 101;
I’m getting,
Arithmetic overflow error converting expression to data type int.
Any idea on what is the cause of it?
I’m just following the instructions in this answer.
asked May 23, 2017 at 16:55
Evan CarrollEvan Carroll
58.9k42 gold badges216 silver badges442 bronze badges
For values larger than the INT max (2,147,483,647), you’ll want to use COUNT_BIG(*).
SELECT COUNT_BIG(*) AS [Records], SUM(t.Amount) AS [Total]
FROM dbo.t1 AS t
WHERE t.Id > 0
AND t.Id < 101;
If it’s happening in the SUM, you need to convert Amount to a BIGINT.
SELECT COUNT(*) AS [Records], SUM(CONVERT(BIGINT, t.Amount)) AS [Total]
FROM dbo.t1 AS t
WHERE t.Id > 0
AND t.Id < 101;
answered May 23, 2017 at 16:56
![]()
Erik DarlingErik Darling
35.5k14 gold badges124 silver badges339 bronze badges
0
When I run this command with SUM()
SELECT COUNT(*) AS [Records], SUM(t.Amount) AS [Total]
FROM dbo.t1 AS t
WHERE t.Id > 0
AND t.Id < 101;
I’m getting,
Arithmetic overflow error converting expression to data type int.
Any idea on what is the cause of it?
I’m just following the instructions in this answer.
asked May 23, 2017 at 16:55
Evan CarrollEvan Carroll
58.9k42 gold badges216 silver badges442 bronze badges
For values larger than the INT max (2,147,483,647), you’ll want to use COUNT_BIG(*).
SELECT COUNT_BIG(*) AS [Records], SUM(t.Amount) AS [Total]
FROM dbo.t1 AS t
WHERE t.Id > 0
AND t.Id < 101;
If it’s happening in the SUM, you need to convert Amount to a BIGINT.
SELECT COUNT(*) AS [Records], SUM(CONVERT(BIGINT, t.Amount)) AS [Total]
FROM dbo.t1 AS t
WHERE t.Id > 0
AND t.Id < 101;
answered May 23, 2017 at 16:56
![]()
Erik DarlingErik Darling
35.5k14 gold badges124 silver badges339 bronze badges
0
SELECT
DATEPART(YEAR, dateTimeStamp) AS [Year]
, DATEPART(MONTH, dateTimeStamp) AS [Month]
, COUNT(*) AS NumStreams
, [platform] AS [Platform]
, deliverableName AS [Deliverable Name]
, SUM(billableDuration) AS NumSecondsDelivered
Предполагая, что ваш цитируемый текст является точным текстом, один из этих столбцов не может выполнять математические вычисления, которые вам нужны. Дважды щелкните ошибку, и она выделит строку, которая вызывает проблемы (если она отличается от опубликованной, ее может не быть); Я проверил ваш код с переменными, и проблем не возникло, а это означает, что один из этих столбцов (о котором мы не знаем более конкретной информации) создает эту ошибку.
Одно из ваших выражений должно быть приведено/преобразовано в int, чтобы это произошло, что является значением Arithmetic overflow error converting expression to data type int.
- 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
-
Marked as answer by
-
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
-
Marked as answer by
-
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
-
Marked as answer by
-
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
-
Marked as answer by
Главная » Основные форумы » Система QUIK
Страницы:
1
|
Leff
Сообщений: 63 |
#1 16.06.2015 21:48:12 [Microsoft][SQL Server Native Client 10.0][SQL Server]Ошибка арифметического переполнения при преобразовании expression к типу данных int. SQLSTATE=22003 Код ошибки=8115 ODBC_ERROR Как узнать на какое поле какой таблицы ругается? PS хелп свежий. седня качал. почему ничего в нем нет про таблицу транзакций? |
|
Alexey Ivannikov
Сообщений: 1275 |
#2 16.06.2015 21:56:32
Добрый день. Как вариант — посмотреть в логе, создав quik_odbc.log. Как создать файл с именем quik_odbc.log: |
||
|
Leff
Сообщений: 63 |
#3 16.06.2015 22:05:42
спасибо за оперативность. пробую |
||
|
Leff
Сообщений: 63 |
#4 16.06.2015 22:13:40
сделал. пока тишина — ошибок нет. неохота завтра нарваться в рабочем режиме |
||
|
Leff
Сообщений: 63 |
#5 16.06.2015 22:20:30 так. ошибка снова. лог куда слать? я посмотрел но ничо не понял. мало инфы в нем |
|
Alexey Ivannikov
Сообщений: 1275 |
#6 16.06.2015 22:27:23
Добрый день. quiksupport@arqatech.com |
||
|
Leff
Сообщений: 63 |
#7 16.06.2015 22:28:45
ушло |
||
|
Leff
Сообщений: 63 |
#8 16.06.2015 22:42:58 ошибка вышла в 22:14:02 похоже (если верить предыдущей записи) что на таблицу всех сделок. |
|
Leff
Сообщений: 63 |
#9 16.06.2015 22:49:32 похоже нашел. по номеру сделки перед ошибкой: толи кол-во толи 3 милиарда не вошло. |
|
Alexey Ivannikov
Сообщений: 1275 |
#10 16.06.2015 22:54:40
Добрый день. Ответили Вам на почту. P.S. Скорее всего у Вас формат для объёма в ТВС стоит неверный. |
||||
Страницы:
1
Читают тему (гостей: 2)
|
Aumi 20 / 35 / 14 Регистрация: 08.10.2015 Сообщений: 406 |
||||||||
|
1 |
||||||||
Ошибка арифметического переполнения05.02.2018, 12:38. Показов 9839. Ответов 3 Метки нет (Все метки)
Здравствуйте, Есть таблица1 (idtovar, price,amount,itog)
В таблице заполнены все столбцы, кроме itog. Есть процедура, которая заполняет этот столбец
если я в таблицу добавлю одну строчку и выполню процедуру, то ошибки нет. Код Сообщение 8115, уровень 16, состояние 2, процедура UpdateSumDelta, строка 43 Ошибка арифметического переполнения при преобразовании expression к типу данных smallmoney. Выполнение данной инструкции было прервано. Откуда взялось expression? Как бороться с ошибкой?
__________________
0 |
|
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
05.02.2018, 12:38 |
|
3 |
|
1107 / 753 / 181 Регистрация: 27.11.2009 Сообщений: 2,241 |
|
|
05.02.2018, 12:49 |
2 |
|
Откуда взялось expression? Amount*Price
В таблице заполнены все столбцы, кроме itog. А зачем что-то хранить, если можно просто сделать вычисляемое поле itog AS Amount*Price??
0 |
|
20 / 35 / 14 Регистрация: 08.10.2015 Сообщений: 406 |
|
|
05.02.2018, 12:51 [ТС] |
3 |
|
iap, У меня участвуют небольшие цены, поэтому взяла smallmoney.
Лучше MONEY или DEC(длина, точность) подходящего размера это вместо float использовать?
0 |
|
1107 / 753 / 181 Регистрация: 27.11.2009 Сообщений: 2,241 |
|
|
05.02.2018, 13:00 |
4 |
|
РешениеПриоритет типов данных (Transact-SQL) Добавлено через 2 минуты
iap, У меня участвуют небольшие цены, поэтому взяла smallmoney. это вместо float использовать? Я ж говорю, лучше не далать itog постоянным полем, а сделать вычисляемым. Добавлено через 3 минуты
iap, У меня участвуют небольшие цены, поэтому взяла smallmoney. Результат умножения будет приведён к типу сомножителя с бОльшим приритетом типа.
1 |
|
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
05.02.2018, 13:00 |
|
4 |

Сообщение было отмечено Aumi как решение