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

I keep getting this error message everytime I run this query:

Msg 8115, Level 16, State 8, Line 33
Arithmetic overflow error converting numeric to data type numeric.
The statement has been terminated.

But if I change the create table to (7,0), I don’t get the error message.But I need my data to be displayed as a decimal. I have tried 8,3 does not work.

Is there any one who can help me work this?Any help will be greatly appreciated.

DECLARE @StartDate AS DATETIME
DECLARE @StartDate_y AS DATETIME
DECLARE @EndDate AS DATETIME
DECLARE @temp_y AS DATETIME

SET @temp_y = Dateadd(yy, Datediff(yy, 0, Getdate()), 0)
SET @StartDate_y = Dateadd(dd, 1 - Datepart(dw, Dateadd("ww", -2, @temp_y)),
                                      Dateadd("ww", -2, @temp_y))
SET @StartDate = Dateadd(dd, 1 - Datepart(dw, Dateadd("ww", -2, Getdate())),
                                  Dateadd("ww", -2, Getdate()))
SET @EndDate = Dateadd(dd, 6, @StartDate)

--temp table to hold all cities in list
CREATE TABLE ##temp
  (
     city VARCHAR(50)
  )

INSERT INTO ##temp
VALUES     ('ABERDEEN'),
            ('CHESAPEAKE'),
            ('Preffered-Seafood/CHICAGO'),
            ('Preffered-Redist/CHICAGO'),
            ('CLACKAMAS'),
            ('COLUMBUS'),
            ('CONKLIN'),
            ('DENVER'),
            ('FORT WORTH'),
            ('HANOVER PARK'),
            ('JACKSONVILLE'),
            ('LAKELAND'),
            ('MONTGOMERY'),
            ('PFW-NORTHEAST'),
            ('PFW-SOUTHEAST'),
            ('RIVERSIDE'),
            ('TRENTON,CANADA'),
            ('VERNON')

--temp to hold data for the cities
CREATE TABLE #temp
  (
     city            VARCHAR(50),
     ytdshipments    INT,
     ytdtotalweight  DECIMAL(7, 2) NOT NULL,
     ytdtotalcharges DECIMAL (7, 2) NOT NULL
  --YTDRevperPound decimal (7,2) not null
  )

INSERT INTO #temp
SELECT ##temp.city,
       0,
       0,
       0
FROM   ##temp

INSERT #temp
-- YTD shipments/Charges/Weight by city
SELECT city = CASE
                WHEN nameaddrmstr_1.city IN( 'ABERDEEN', 'CHESAPEAKE', 'CHICAGO'
                                             ,
                                             'CLACKAMAS',
                                             'COLUMBUS', 'CONKLIN', 'DENVER',
                                             'FORT WORTH',
                                             'HANOVER PARK', 'JACKSONVILLE',
                                             'LAKELAND'
                                             ,
                                             'MONTGOMERY'
                                                    ,
                                             'RIVERSIDE', 'TRENTON', 'VERNON' )
              THEN
                CASE
                  WHEN
              nameaddrmstr_1.city = 'CHICAGO'
              AND h.shipr = 'PREFRESVS' THEN 'Preffered-Redist/CHICAGO'
                WHEN
              nameaddrmstr_1.city = 'TRENTON'
              AND nameaddrmstr_1.city = 'CA' THEN 'TRENTON,CANADA'
                ELSE
              nameaddrmstr_1.city
                END
                ELSE 'Other'
              END,
       ytdshipments = COUNT(CONVERT(VARCHAR(10), h.dateshipped, 101)),
       ytdtotalweight =SUM(CASE
                             WHEN h.totaldimwgt > h.totalwgt THEN h.totaldimwgt
                             ELSE h.totalwgt
                           END),
       ytdtotalcharges = SUM (cs.totalestrevcharges)
--YTDRevperPound = convert(decimal(7,2),sum (cs.TotalEstRevCharges )/sum( CASE WHEN h.TotalDimWGT > > h.TotalWGT THEN h.TotalDimWGT ELSE h.TotalWGT END ))
FROM   as400.dbo.hawb AS h WITH(nolock)
       INNER JOIN as400.dbo.chargesummary AS cs
         ON h.hawbnum = cs.hawbnum
       LEFT OUTER JOIN as400.dbo.nameaddrmstr AS nameaddrmstr_1
         ON h.shipr = nameaddrmstr_1.nameaddrcode
WHERE  h.dateshipped >= '01/01/2010'
       AND h.dateshipped <= '12/19/2010'
       --WHERE H.DateShipped >= >= @StartDate_y AND H.dateshipped <= @EndDate 
       AND h.cust IN( 'DARDENREED', 'MAINEDARDE', 'MBMRIVRSDE', 'MBMCOLUMBS',
                      'MBMLAKELND', 'MBMFTWORTH', 'SYGMACOLUM', 'SYGMANETW6',
                      'MAI215', 'MBMMNTGMRY' )
GROUP  BY CASE
  WHEN nameaddrmstr_1.city IN( 'ABERDEEN', 'CHESAPEAKE', 'CHICAGO', 'CLACKAMAS',
                               'COLUMBUS', 'CONKLIN', 'DENVER', 'FORT WORTH',
                               'HANOVER PARK', 'JACKSONVILLE', 'LAKELAND',
                               'MONTGOMERY'
                                      ,
                               'RIVERSIDE', 'TRENTON', 'VERNON' ) THEN CASE
                                                                         WHEN
nameaddrmstr_1.city = 'CHICAGO'
AND h.shipr = 'PREFRESVS' THEN 'Preffered-Redist/CHICAGO'
                                                                         WHEN
nameaddrmstr_1.city = 'TRENTON'
AND nameaddrmstr_1.city = 'CA' THEN 'TRENTON,CANADA'
                                                                         ELSE
nameaddrmstr_1.city
                                                                       END
  ELSE 'Other'
END

SELECT #temp.city                 AS city,
       MAX(#temp.ytdshipments)    AS ytdshipments,
       MAX(#temp.ytdtotalweight)  AS ytdtotalweight,
       MAX(#temp.ytdtotalcharges) AS ytdtotalcharges
FROM   #temp WITH(nolock)
       LEFT OUTER JOIN ##temp
         ON ##temp.city = #temp.city
GROUP  BY #temp.city

DROP TABLE #temp

DROP TABLE ##temp  

В работе клиент серверной 1С иногда появляется сообщение:

Ошибка выполнения запроса
по причине:
Ошибка при выполнении операции над данными:
Microsoft OLE DB Provider for SQL Server: Arithmetic overflow error converting numeric to data type numeric.
HRESULT=80040E57, SQLSrvr: SQLSTATE=22003, state=8, Severity=10, native=8115, line=1

Если данная ошибка появляется под управлением  MS SQL 2000, то рекомендуется проверить и установить обновление SP до SP4.

Но для SQL 2005 и 2008 появление такой ошибки не решается обновлением сервиспака.

Вообще появление указанной ошибки вызвано ошибкой в MS SQL при выполнении операции округления, например:

. касательно 1С и запросов выполняемых в ней, указанная ошибка может появляться при выполнении команды: ВЫРАЗИТЬ(ЕСТЬNULL(ВремяПоГрафикуВЧасахНорма, 0) КАК ЧИСЛО(5, 2)) КАК WorkingHours

Если в качестве операнда будет число со значением после запятой .5, в этом случае SQL считает/разбирает значение как литерал х.5 и преобразует к данным типа Numeric(2,1). Функция ROUND (округления)  отрабытывает правильно получая округленный результат и затем пытается сохранить как данные в формате Numeric(2,1), что не правильно и мы получаем сообщение «arithmetic overflow».

Если у Вас возникает такая ошибка, то попробуете использвать преобразование:

ВЫРАЗИТЬ(ЕСТЬNULL(ВремяПоГрафикуВЧасахНорма, 0) КАК ЧИСЛО(  {НОВОЕ значение} , 2)) КАК WorkingHours

, ГДЕ

     {НОВОЕ значение} — Это увеличенное на один (несколько) разряд значение, в это случае ошибки не будет возникать.

Автор решения Александр Шарафан

 +3 

   

Распечатать

Если запрос не выполняется с такой вот руганью:


{Форма.Форма.Форма(804)}: Ошибка при вызове метода контекста (Выполнить): Ошибка выполнения запроса: Ошибка при выполнении операции над данными:Microsoft SQL Server Native Client 11.0: Ошибка арифметического переполнения при преобразовании numeric к типу данных numeric.HRESULT=80040E57, SQLSrvr: SQLSTATE=22003, state=8, Severity=10, native=8115, line=1


Решение следующее (если у кого будет еще что-то прошу добавлять ).

1. В запросе использую расчет процента:

Код 1C v 8.х

 ВЫРАЗИТЬ(втИтоги.КоличествоОборот / втИтоги.ПланМП1 * 100 КАК ЧИСЛО(5, 2)) КАК ПроцентВыполнения,   

Изменив выражение с (5,2) на (15,2) запрос «взлетел»:

Код 1C v 8.х

 ВЫРАЗИТЬ(втИтоги.КоличествоОборот / втИтоги.ПланМП1 * 100 КАК ЧИСЛО(15, 2)) КАК ПроцентВыполнения,

Получается что ошибка: «Ошибка арифметического переполнения при преобразовании numeric к типу данных numeric» нам говорит что результат вычисления процента длиной больше чем 5.

Пример обычного кода:Реквизит1 = Тип число (5,2).РасчетПроцента = 1234,56.Реквизит1 = РасчетПроцента;Реквизит1 = 999,99.

Успехов в решении проблем.С уважением, Сергей.

This error comes when you try to store an out-of-range floating point value into a numeric variable. For example, if your NUMERIC or DECIMAL variable is defined as NUMERIC(5,2) then the maximum value it can hold is 999.99, if you try to store something like 1000.00 then it will throw «Arithmetic overflow error converting numeric to data type numeric». One of the common reasons for this error is the ignorance and misunderstanding of the NUMERIC data type. For example, many SQL Server DBAs and developers think that a NUMERIC(5,2) variable can hold a 7 digit floating point number where 5 digits are before the decimal and 2 digits are after the decimal. This is wrong.

A NUMERIC(5,2) means, the total number of digits in the value cannot exceed 5 and decimal precision is 2 digits i.e. the maximum possible value is 999.99.

Another thing SQL programmers don’t know and remember about NUMERIC or DECIMAL data types in Microsoft SQL Server is that it doesn’t throw this error if you specify more digits than permitted after the decimal point, instead, it does rounding for example if you store 100.999 then it will store 101.00 after rounding.

Here is an SQL query to prove these points:

DECLARE @sample NUMERIC(5,2)
SET @sample = 1000.554
SELECT @sample

Output
Arithmetic overflow error converting numeric to data type numeric.

Explanation: 

This time SQL Server throws the error because we are trying to store 1000 but the maximum value a NUMERIC(5,2) can hold is 999 before the decimal point. You need to increase the width of the variable to store this number e.g. making @sample NUMERIC(6,2) will solve this error as shown below.

By the way, if you are new to Microsoft SQL Server and T-SQL then I also suggest you join a comprehensive course to learn SQL Server fundamentals and how to work with T-SQL. If you need a recommendation then I suggest you go through the Microsoft SQL for Beginners online course by Brewster Knowlton on Udemy. It’s a great course to start with T-SQL and SQL queries in SQL Server.

Arithmetic overflow error converting numeric to data type numeric in SQL Server

Arithmetic overflow error converting numeric to data type numeric in SQL Server Examples

Here are some more SQL queries which will confirm the behavior of the NUMERIC variable and its range:

DECLARE @sample NUMERIC(5,2)
SET @sample = 100.554 // no rounding because the extra digit is less than 5
SELECT @sample AS Result

Result
100.55

DECLARE @sample NUMERIC(5,2)
SET @sample = 100.555 // rounding will happen
SELECT @sample AS Result

Result
100.56


DECLARE @sample NUMERIC(5,2)
SET @sample = 100.55 // no rounding because value is under defined precision
SELECT @sample AS Result

Result
100.55


DECLARE @sample NUMERIC(5,2)
SET @sample = 100.999 // Rounding to nearest value
SELECT @sample AS Result

Result
101.00

DECLARE @sample NUMERIC(5,2)
SET @sample = 999.999 // error because after rounding value will be
                      // out-of-range for defined numeric type
SELECT @sample AS Result

Result
Arithmetic overflow error converting numeric to data type numeric.

That’s all about «Arithmetic overflow error converting numeric to data type numeric in SQL Server». You can see that cause of the error is usually out-of-range value for the defined NUMERIC type. Just check the source of value and correct or increase the precision level of your column.

Always remember that NUMERIC(5,2) means a total of 5 digits with 2 digits after the decimal point, and the maximum value it can hold is 999.99. Beware of rounding due to more additional digits after the decimal point, which can also cause «Arithmetic overflow error converting numeric to data type numeric» in Microsoft SQL Server.

Related SQL Server articles you may like to explore

  • Difference between rank(), row_number(), and dense_rank() in SQL? (answer)
  • How to replace NULL with empty String in SQL Server? (tutorial)
  • Difference between Cast, Convert, and Parse method in SQL? (answer)
  • Difference between coalesce() and isNull() in Microsoft SQL Server? (answer)
  • How to remove duplicate rows from a table in SQL? (solution)
  • How to create an Identity column in SQL Server? (example)
  • How to format Date in Microsoft SQL Server? (example)
  • 5 Web sites to learn SQL online for FREE? (resource)
  • How to find the length of a string in SQL Server? (example)
  • How to convert the result of a SELECT command into a CSV String? (example)
  • The right way to check for NULL values in the SQL query? (example)
  • How to split String in SQL Server? (answer)
  • What is the difference between close and deallocate a cursor? (answer)
  • How to find all customers who have never ordered? (solution)
  • The right way to compare dates in SQL query? (example)
  • How to add columns into an existing table in MSSQL? (example)

Thanks for reading this article. If you like the information given here and my explanation then please share it with your friends and colleagues. 

  • Remove From My Forums
  • Question

  • Declare @Number Numeric(5,2)=0.2500
    Declare @pagebreak INT =500
    Declare @result Numeric(5,2)

    Select @result=  @pagebreak/@Number

    I increased the @result datatype value , still i am getting error

    Msg 8115, Level 16, State 8, Line 6

    Arithmetic overflow error converting numeric to data type numeric.

Answers

    • Proposed as answer by

      Wednesday, November 6, 2013 6:33 AM

    • Marked as answer by
      Allen Li — MSFT
      Thursday, November 14, 2013 1:12 PM
  • Declare @Number Numeric(5,2)=0.2500
    Declare @pagebreak INT =500
    Declare @result Numeric(5,2)

    Select @result=  @pagebreak/@Number

    I increased the @result datatype value , still i am getting error

    Msg 8115, Level 16, State 8, Line 6

    Arithmetic overflow error converting numeric to data type numeric.

    The result of this calculation is 2000 but the @result variable is only numeric(5,2), allowing a max value of 999.99.  You need to increase to (at least) numeric(6,2).


    Dan Guzman, SQL Server MVP, http://www.dbdelta.com

    • Proposed as answer by
      Allen Li — MSFT
      Wednesday, November 6, 2013 6:33 AM
    • Marked as answer by
      Allen Li — MSFT
      Thursday, November 14, 2013 1:12 PM

  • Ошибка арифметического переполнения при преобразовании int к типу данных numeric
  • Ошибка аср фольксваген гольф
  • Ошибка аср мерседес w210
  • Ошибка асп на кассе миника
  • Ошибка аскуэ этап опрос счетчика счетчик не отвечает