This select statement gives me the arithmetic error message:
SELECT CAST(FLOOR((CAST(LeftDate AS DECIMAL(12,5)))) AS DATETIME), LeftDate
FROM Table
WHERE LeftDate > '2008-12-31'
While this one works:
SELECT CAST(FLOOR((CAST(LeftDate AS DECIMAL(12,5)))) AS DATETIME), LeftDate
FROM Table
WHERE LeftDate < '2008-12-31'
Could there be something wrong with the data (I’ve checked for null values, and there are none)?
gbn
417k81 gold badges581 silver badges670 bronze badges
asked Mar 11, 2009 at 9:24
Found the problem to be when a date was set to 9999-12-31, probably to big for the decimal to handle. Changed from decimal to float, and every thing is working like a charm.
answered Mar 11, 2009 at 9:38
oekstremoekstrem
4773 gold badges6 silver badges12 bronze badges
In general, converting a date to a numeric or string, to perform date operations on it, is highly inefficient. (The conversions are relatively intensive, as are string manipulations.) It is much better to stick to just date functions.
The example you give is (I believe) to strip away the time part of the DateTime, the following does that without the overhead of conversions…
DATEADD(DAY, DATEDIFF(DAY, 0, <mydate>), 0)
This should also avoid arithmentic overflows…
answered Mar 11, 2009 at 14:12
![]()
MatBailieMatBailie
81.3k18 gold badges101 silver badges137 bronze badges
2
Maybe this helps someone since my problem was a bit different.
The SELECT that was throwing this error had many nested SELECTs and many date comparisons with arithmetic operations like GETDATE() - CloseDate.
The result of such operations was then being compared to '1900-01-01' again mentioned many times in the nested SELECTs.
My solution was to declare variables for result of GETDATE() and datetime variable for '1900-01-01' to avoid conversions.
Declare @CurrentDate datetime = GetDate()
Declare @BlankDate datetime = '1900-01-01'
...
... @CurrentDate - CloseDate ...
... CloseDate <> @BlankDate ...
The DATEADD(DAY, DATEDIFF(DAY, 0, <mydate>), 0) bit from MatBailie’s answer was also helpful.
answered Mar 5, 2019 at 12:21
- Remove From My Forums
-
Question
-
Unable to conver it…
create procedure temp(empid int, todaydate datetime)
as
begin
select * from table where todaydate = lastdate;
end
here lastdate
is INT TYPEgetting Arithmetic overflow error converting expression to data type datetime.
pls help it.
Answers
-
CREATE PROCEDURE temp ( empid INT ,todaydate DATETIME ) AS BEGIN SELECT * FROM mytable WHERE todaydate = cast(lastdate AS DATETIME) END
-Vaibhav Chaudhari
-
Marked as answer by
Thursday, November 27, 2014 2:56 PM
-
Marked as answer by
I need help in the following issue
I have created a procedure for the purpose of fetching the yesterday data from oracle db table and insert it into sql server db table 2012.
Using the following
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
SELECT
lead(convert(varchar,convert(datetime,'01-JAN-1970 03:00:00',120) + [DAT_CLOSEDATE]/(24*60*60), 120),1,convert(varchar,convert(datetime,'01-JAN-1970 03:00:00',120) + [DAT_CLOSEDATE]/(24*60*60), 120)) over(partition by [TXT_TICKETNUMBER] order by [DAT_CLOSEDATE])AS [CLOSE_DATE]
INTO #Temp
FROM OPENQUERY(ORACLE_DB, 'SELECT DAT_CLOSEDATE ,TXT_TICKETNUMBER FROM SCHEME.TABLE')
WHERE [DAT_CLOSEDATE] = DATEADD(d,-1,GETDATE())
SELECT * FROM #Temp
every thing is working as expected when I don’t use the WHERE
condition.
but once I use the WHERE condition the following error appears
Msg 8115, Level 16, State 2, Line 4 Arithmetic overflow error converting expression to data type datetime. The statement has been terminated.
NOTE:
The DAT_CLOSEDATE column datatype in the oracle table is float.
I used the LEAD AND CONVERT functions in order to convert its values to be a
datetime datatype
I have tried to convert it to date datatype as following.
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
SELECT
lead(convert(varchar,convert(date,'01-JAN-1970 03:00:00',120) + [DAT_CLOSEDATE]/(24*60*60), 120),1,convert(varchar,convert(date,'01-JAN-1970 03:00:00',120) + [DAT_CLOSEDATE]/(24*60*60), 120)) over(partition by [TXT_TICKETNUMBER] order by [DAT_CLOSEDATE])AS [CLOSE_DATE]
INTO #Temp
FROM OPENQUERY(ORACLE_DB, 'SELECT DAT_CLOSEDATE ,TXT_TICKETNUMBER FROM SCHEME.TABLE')
WHERE [DAT_CLOSEDATE] = DATEADD(d,-1,GETDATE())
SELECT * FROM #Temp
But I got this error
Msg 206, Level 16, State 2, Line 4 Operand type clash: date is incompatible with float
Problem
Arithmetic overflow error converting expression to data type datetime
Symptom
LWJDBC adapter fails when updating a column with a time that has an hour
value of 24.
The business process was using the «TimestampUtilService»
with this parameter yy/MM/dd kk:mm:ss:SSS
The kk value generates the
hour in the range 1-24.
This was causing the error in the LWJDBC adapter
when updating an external SQL database.
Error Message
8115: [Microsoft][SQLServer 2000
Driver for JDBC][SQLServer]Arithmetic overflow error converting expression to
data type datetime
Resolving The Problem
Solution
Replace this yy/MM/dd kk:mm:ss:SSS with yy/MM/dd HH:mm:ss:SSS
HH
will generate an hour in the range 00 to 23.
[{«Product»:{«code»:»SS3JSW»,»label»:»IBM Sterling B2B Integrator»},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Component»:»Extensions»,»Platform»:[{«code»:»PF025″,»label»:»Platform Independent»}],»Version»:»All»,»Edition»:»»,»Line of Business»:{«code»:»LOB59″,»label»:»Sustainability Software»}},{«Product»:{«code»:»SS3JSW»,»label»:»IBM Sterling B2B Integrator»},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Component»:»Adapters»,»Platform»:[{«code»:»»,»label»:»»}],»Version»:»»,»Edition»:»»,»Line of Business»:{«code»:»LOB59″,»label»:»Sustainability Software»}}]
Historical Number
TRB2400
I have such an issue. I want to select a column PDWEDT (it is numeric) and I need to select previous Saturday. The way how I usually do is with the help of declare statement
Text
DECLARE @CurrentWeekday INT = DATEPART(WEEKDAY, GETDATE()) DECLARE @LastSunday DATETIME = DATEADD(day, -1 * (( @CurrentWeekday % 7) - 1), GETDATE());
Afterwards, I have some code and later I just try to select the dates
Text
AND p.[PDWEDT] = @LastSunday
Not sure why but I am getting an error: «Arithmetic overflow error converting expression to data type datetime.»
So I see 2 potential ways to solve this problem.
1. Either to find another way to select previous Saturday instead of DECLARE statements (though as I understand it is the most common way). or 2. To cast or convert the field, however I am not sure how it can be done since it is numeric at the very moment. I will appreciate any ideas. Thank you. p/s I use SQL Server Management Studio.
check
Best Answer

jrp78

This person is a verified professional.
Verify your account
to enable IT peers to see that you are a professional.
ghost chili
Microsoft SQL Server Expert
-
check
36
Best Answers -
thumb_up
79
Helpful Votes
Ahh, the code was getting sunday not saturday, try this.
EDIT: one correction
SQL
CONVERT(DATE, CONVERT(CHAR(8), p.PDWEDT )) = cast(DATEADD(dd, DATEPART(DW,GETDATE())*-1, GETDATE()) as date)
1 found this helpful
thumb_up
thumb_down
View Best Answer in replies below
Read these next…

WINDOWS 10 «glitch» — file explorer
Windows
Hi.I have been experiencing a black line (glitch) on my file explorer which comes for milliseconds then it goes away. See screen grab. Is there anyone who has experienced such and how were they able to solve it?Thank you.

Are you updating workstations to Windows 11?
Windows
Has anyone started updating workstations on a AD domain to Windows 11? what type of issues are you facing?What is the user reaction been?Thanks!

Snap! — Psyche Probe, DIY Gene Editing, RaiBo, AI handwriting, Metric Pirates
Spiceworks Originals
Your daily dose of tech news, in brief.
Welcome to the Snap!
Flashback: January 27, 1880: Thomas Edison receives patent for the Electric Lamp. (Read more HERE.)
Bonus Flashback: January 27, 1967: Apollo 1 Tragedy (Read more HERE.)
You …

NEC Inmail Email doesn’t Change
Collaboration
Hey Everyone,Recently a client of mine wanted to change the email to their QA extension to her email as to help keep voicemails consolidated instead of spread out among different emails. Normally this wouldn’t be a huge deal. Logged in to to Webpro, hoppe…

I inherited some really cool equipment. I just have no clue how to use it!
Hardware
So I’ve got some switches, and some servers. The switches seem pretty straight forward, plug in packet go zoom, but I have no clue how these servers work. They’re headless rack servers. I know there must be a way to get some kind of UI going with a monito…
Вопрос:
При выполнении следующей ошибки отображается
declare @yr_mnth_dt as numeric;
set @yr_mnth_dt = 20130822;
select convert(datetime,@yr_mnth_dt,112) as YR_MNTH_DT
ошибка показывает
Arithmetic overflow error converting expression to data type datetime.
Лучший ответ:
Вы указываете, что вы пытаетесь convert использовать числовое значение , и это просто не работает.
Вам нужно сначала превратить ваш numeric в строку:
declare @yr_mnth_dt as numeric;
set @yr_mnth_dt = 20130822;
select yr_mnth_dt = cast(cast(@yr_mnth_dt as char(8)) as datetime);
SQL Fiddle с демонстрацией.
Когда вы пытаетесь преобразовать числовой тип в datetime, SQL Server пытается добавить числовое значение как число дней до даты 01-Jan-1900. В вашем случае это пытается добавить миллионы дней и, следовательно, ошибку переполнения.
convert отлично работает, если вы предпочитаете:
select yr_mnth_dt = convert(datetime, convert(char(8), @yr_mnth_dt));
SQL Fiddle с демонстрацией.
Ответ №1
Я видел только преобразование, используемое для строк. Я не могу легко сказать, даже он предназначен для работы с числами. Вы можете преобразовать число в строку, а затем строку в дату. Однако я бы просто использовал DATEFROMPARTS:
SELECT DATEFROMPARTS(@yr_mnth_dt / 10000,
(@yr_mnth_dt / 100) % 100,
@yr_mnth_dt % 100) AS YR_MNTH_DT
Ответ №2
Почему числовое?
Попробуйте это
declare @yr_mnth_dt as varchar(10);
set @yr_mnth_dt = '20130822';
select convert(datetime,@yr_mnth_dt,112) as YR_MNTH_DT
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
I don’t know if anyone has given you the Stern Lecture for using a non-datetime datatype to contain datetime data, but if not, consider it done.
That being said, and with the realization that we can’t always control the form of the data sent to us from outside our domain, here is one solution. I’ve even fixed the IsDate problem. By using date arithmetic rather than conversion (limiting CONVERT to change the numeric to integer so we can use modulo), all values between the two extremes will generate a valid date — although, if someone entered the date 20080231 which is not a valid date, the result will be 2008-02-29, which is a valid date but not necessarily the correct date (the date the user meant to enter). Since this will not result in an error, it may not be the result you want.
declare @test-2 table(
FirstDispursementDate numeric( 8, 0 )
);
Insert @test-2( FirstDispursementDate )
select 20020405 union all
select 20041222 union all
select 20001111 union all
select 20060223 union all
select 19991110 union all
select 19980425 union all
select 19991118 union all
select 20080723 union all
select 20020813 union all
select 17500723 union all -- Bogus date
select 20070231 union all -- Looks bad but converts to 2007-02-28
select 20029999 union all -- Looks bad but converts to 2010-06-09
select 20029901 union all -- Looks bad but converts to 2010-03-01
select 99991231 union all
select 0; -- Bogus date
-- All calculations in one statement
select FirstDispursementDate as AsNumeric,
DateAdd( mm, ((Convert( int, FirstDispursementDate / 10000 ) - 1900) * 12 )
+ ((Convert( int, FirstDispursementDate ) % 10000) / 100) - 1,
DateAdd( dd, (Convert( int, FirstDispursementDate ) % 100) - 1, 0 ))
as AsDatetimeValue
from @test-2
where FirstDispursementDate between 17530101 and 99991231; -- Fullproof "IsDate" function
-- The same calculations but separated into nested derived tables for purposes
-- of illustration only.
-- First convert numeric to int (x), then split int value into three values for
-- year, month and day (y) and finally manipulate to make a datetime value.
select DateAdd( mm, ((FDDYear - 1900) * 12) + FDDMonth - 1,
DateAdd( dd, FDDDay - 1, 0 )) as AsDatetimeValue
from(
select FirstDispursementDate / 10000 as FDDYear,
FirstDispursementDate % 10000 / 100 as FDDMonth,
FirstDispursementDate % 100 as FDDDay
from(
select Convert( int, FirstDispursementDate ) as FirstDispursementDate
from @test-2
where FirstDispursementDate between 17530101 and 99991231
) x
) y;
Tomm Carr
—
Version Normal Form — http://groups.google.com/group/vrdbms
Содержание
- Sql native error 8115
- Answered by:
- Question
- Answers
- All replies
- Life of a support engineer!!
- Monday, August 31, 2009
- «Arithmetic overflow error converting expression to data type datetime.Native error: 8115 SQLState: 22003» error message in Microsoft SQL
- Sql native error 8115
- Вопрос
- Ответы
- Ошибка SQL: Arithmetic overflow error converting numeric to data type numeric
- Специальные предложения
- См. также
- Реструктуризация базы в 1С: для чего требуется и о назначении в целом
- Копии баз данных и размер БД. Проблемы и пути решения
- Работа с файлом *.dt формата
- Регистрация в центре лицензирования не выполнена
- Настройка отказоустойчивого кластера 1C + PostgreSQL (etcd+patroni+haproxy) на Centos 8
- Workaround me в 1С/MS SQL и не только, системный подход к созданию костылей
- Ошибка Dump в 1С
- Режимы запуска системы 1С:Предприятие
- Оптимизация высоконагруженных конфигураций: история маленькой победы, или советы тем, кто столкнулся с проблемой впервые и не знает, что делать
- Ошибка формата потока расширения
- Пропадающие файлы на томе в 1С: КА 2.5
- Ошибка загрузки большого архива 1Cv8.dt в PostgresSQL на платформе 1С 8.3.19
- SAMBA для 1С
- Регламентное задание по завершению сеансов пользователей 1С
- Базовые приемы работы с кластером 1С при помощи БСП
Sql native error 8115
![]()
Answered by:

Question


I get Arithmetic overflow error converting expression to data type float in sql server 2012 and my crystal report generation fails (version 13).
Similarly when i run it in sql server 2008, I get the same arithmetic overflow error converting expression to data type float but my crystal report gets generated.
Any help regarding this.
Answers


Tumse na ho payega Sayali,
check XACT_ABORT function
and check the connection. Use SQL Server connection rather SQL Server Native Client.


Hi Sayali Tavare,
Thank you for your post. This issue is more related with Database. About the error message, please refer to the similar cases as below.
Hope this could be helpful to you.


Thanks for replying. My query is regarding crystal report. It gets generated on one environment but fails in the other resulting the arithmetic overflow error. In both the environment I get the same arithmetic overflow error when i execute the Stored Procedure.
What is the difference between error message : Msg 8115, Level 16, State 6 (Sql Server 2012) and Msg 8115, Level 16, State 2 (Sql Server 2008)? (State 6 and State 2)??
Could this be a cause of not generating the report?
Источник
Life of a support engineer!!
I started this blog few years back to keep track of few thing I been working on, decided to put it on blog for sharing purposes in case it helps someone. I or anyone associated with me do not take any responsibility or liability about the contents of this blog. Please consider your options and take really good backups before following anything mentioned here.
Monday, August 31, 2009
«Arithmetic overflow error converting expression to data type datetime.Native error: 8115 SQLState: 22003» error message in Microsoft SQL
Problem Description: Following error message may be thrown by some applications that uses date formats:
» Arithmetic overflow error converting expression to data type datetime.Native error: 8115 SQLState: 22003 «
A application that was working properly earlier can certainly start to throw this error message after some changes were made to the environment. In my usercase a database was moved from one SQL server to another SQL server. Problem started to occur on 13th of month, problem was present till 1st of next month. Problem will come back on 13th of next month.
Cause: Date formats used by service account can cause problem while converting data that is related to calander dates. In my usercase default language for Service Account within Microsoft SQL Server has been changed from one format to another e.g. from English (US_English) to British.
Solution: There are different solutions for it but if a application is already wrote and you only want to resolve the problem of error message following is what you can try.
Note: These steps are written for MS SQL Server 2005 you might want to change it a little for other versions of MS SQL Server
- Log on to SQL server that hosts databases in question.
- Launch ‘SQL Server Management Studio’.
- When prompted, log on using the credentials that will allow you to make changes to the SQL server configuration.
- In the left pane of ‘Microsoft SQL Server Management Studio’ expand ‘Security’ section.
- Further expand ‘Logins’ section.
- Select Service Account and right click on it.
- Select ‘Properties’
- On ‘Login Properties’ screen on right side of the pane check ‘Default Language’ section.
- If ‘Default Language’ is set to British change it to English (or vise versa depending on your needs)
- Select ‘OK’
Language and dateformats specific for a service account can also be checked by running ‘dbcc useroptions’ query analyzer while logged in using service account .
Caution: Please also check with the vendor of the application on what date format is preffered by the application as making changes to date format settings can cause problem with the data that will be stored by service account into the SQL tables.
Источник
Sql native error 8115

Вопрос


We are getting an Arithmetic Overflow Error — 8115
The error is thrown when a formula is getting calculated through the sql query
create table #temp
(
A decimal(21,4),
B decimal(21,4),
C decimal(21,4)
)
Insert into #temp
values( 171577.3139, 3376774.0000,3760846.0000)
select (A)/(0.8770/(B/C)) from
(select avg(A) as A, avg(B) as B, avg(C) as C from #temp) a
On execution of the select statement the following error message is thrown.
Server: Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type numeric.
Can any one help us with a resolution.
Note: This select is part of our stored procedure.This formula is dynamically generated in our code.
We will not in a position to use cast function. We tried trace flag (107) option also. But we dont know how to set it permanently. It is effective only in the respective session. When the stored procedure is called from the application, the trace flag option does not work.
Ответы


Was the sample query suppose to error, or display what you are trying to accomplish? The sample query ran perfect on my instance.
By reading your problem, I would assume SQL is trying to implicity convert you decimal column to a numeric one. The problem is the percision/scale of the implicit conversion is not enough to handle the calculation. You can confirm this by creating an execution plan for the stored procedure. You should see near the problimatic code the words «implicit conversion.»
Should this be the case, you will have to cast or convert the value in the stored procedure; otherwise, SQL will continue implicitly convert the value.
Источник
Ошибка SQL: Arithmetic overflow error converting numeric to data type numeric
По запросу «Arithmetic overflow error converting numeric to data type numeric» есть куча обсуждений и очень мало записано решений. Мой случай, вероятно, частный, но кого-то подтолкнет в направлении «куда копать».
SQL 2016 Standard
Платформа 8.3.18
При выполнении запросов к БД типа:
Когда, количество строк >
10 000 000, выдавалась ошибка:
Решение
Добавлено преобразование типа Число к конкретной длине. Баг перестал воспроизводиться.
Коллеги, если сталкивались с ошибкой, в комментариях опишите причину сбоя, и, если знают — другие способы устранения.
Специальные предложения












int до 2 147 483 647, не думаю, что такое кол-во записей в регистре.
Скорее всего, это игры 1С/MSSQL с precison numeric. Например, рассматривает 1 как Numeric(7,0), пытаясь к нему преобразовать результат СУММА(1).
P.S.
В конкретном примере использование «Сумма», по-моему, неоправдано, ибо Количество(*), скорее-всего выполнится верно.
( а если есть еще индекс по одному из измерений и делать COUNT(OUR_FIELD), то и full index scan не так страшен).
Советы по использованию «Выразить», наверное, относятся к случаю, когда вместо литерала суммируют что-то более осмысленное.
Лезть в профайлер и смотреть во что 1С превращает 1, неохота.
Для подсчета кол-ва записей лучше юзать:
Выбрать Количество(1) Из РегистрНакопления.ТоварыКПоступлению
ну а если нужна сумма, то можно применить такой костыль:
Выбрать Сумма(0.001) Из РегистрНакопления.ТоварыКПоступлению
получите сумму в тысячах )
(4) мысль автора комментария по-моему осталась не законченной.
Заметил и что?
Если решил, то как?
Если знаете решение — почему не поделиться с сообществом?
Кто знает о вашем достижении?
Если по существу — то вы молодец.
(6) наверное, мой навык гугления не такой как ваш.
Видел эту статью.
Там SQL древний описан и я не стал ее читать (зря).
Ничего страшного, если решение будет записано еще раз с указанием более свежей версии SQL.
Обновление 25.08.21 11:18
См. также
Реструктуризация базы в 1С: для чего требуется и о назначении в целом
В статье расскажем о том, как в 1С:Управление торговлей происходит реструктуризация таблиц информационной базы и почему это требуется производить регулярно.
07.12.2022 1103 Koder_Line 4
Копии баз данных и размер БД. Проблемы и пути решения
Столкнулся с проблемой быстрого роста объема БД. Статья о том, как решал эту проблему.
30.11.2022 1069 DrMih 5
Работа с файлом *.dt формата
В статье расскажем о том, что такое *.dt формат, для чего он применяется, как создать *.dt файл, куда и как загружать*.dt файл, а также дадим некоторые советы по работе с *.dt файлами.
29.11.2022 1365 Koder_Line 5
Регистрация в центре лицензирования не выполнена
Каждый пользователь программ 1С сталкивался с ситуацией, когда при входе в программу 1С появляется всплывающая картинка с информацией, что «Регистрация конфигурации в центре лицензирования не выполнена», которая появляется и мешает нам работать. При этом такая ситуация может возникнуть в любой конфигурации 1С.
28.09.2022 1418 Koder_Line 2
Настройка отказоустойчивого кластера 1C + PostgreSQL (etcd+patroni+haproxy) на Centos 8
Настройка отказоустойчивого кластера PostgreSQL для сервера приложений 1С на операционной системе Centos 8.
22.08.2022 2637 user1332168 10
Workaround me в 1С/MS SQL и не только, системный подход к созданию костылей
Workaround свидетельствует о невозможности решить проблему «правильным путем» и вызывает чувство стыда. Но практика показывает, что способность решать проблемы через workaround является порой единственным способом решить проблему в разумное время. А победителей, как говорят, не судят, так почему бы не создавать workaround по системе?
15.08.2022 1080 1CUnlimited 0
Ошибка Dump в 1С
В данной статье будет рассмотрено представление ошибки Dump в 1С, будет проведена её диагностика, а также определено, как устранить данную ошибку и продолжить дальнейшую корректную работу системы 1С. Также будет представлена общая информация об ошибке Memorydump, для более глубокого её понимания.
15.07.2022 1428 Koder_Line 3
Режимы запуска системы 1С:Предприятие
Существует несколько путей установки режимов запуска 1С:Предприятие. Рассмотрим запуски системы в режиме «1С:Предприятие» и в режиме Конфигуратора. Проговорим предварительно, что одновременное использование нескольких режимов не допускается для того, чтобы указать параметры командной строки.
12.07.2022 1812 Koder_Line 1
Оптимизация высоконагруженных конфигураций: история маленькой победы, или советы тем, кто столкнулся с проблемой впервые и не знает, что делать
Пост будет больше интересен руководителям отделов ИТ сопровождения или проектным менеджерам, перед которыми будет стоять задача решения проблемы деградации производительности баз данных 1С. Пост для тех, кому эта тема нова, нет особого опыта, и с ходу непонятно, с чего начать.
24.05.2022 3702 avolsed 15
Ошибка формата потока расширения
Восстановление базы данных 1С с ошибкой «Ошибка формата потока» с «полетевшим» расширением, когда все остальные методы уже испробованы.
19.05.2022 1244 yupi71 9
Пропадающие файлы на томе в 1С: КА 2.5
На протяжении месяца пропадали файлы: прикрепленные изображения, документы в ЭДО. КА 2.5, актуальная редакция на поддержке. Этого не описано НИГДЕ и если бы я нашел такую тему, у меня мы было гораздо меньше проблем.
05.04.2022 1177 mlashko 4
Ошибка загрузки большого архива 1Cv8.dt в PostgresSQL на платформе 1С 8.3.19
1С для платформы 8.3.19 ускорили загрузку dt-файлов за счет разбивки на несколько фоновых заданий. В итоге словили ошибку блокировки при загрузке в СУБД PostgresSQL большого 1cv8.dt-файла размером 25 Gb «ERROR: canceling statement due to lock timeout». Напишу, как в итоге загрузили этот dt-файл.
30.01.2022 8092 sapervodichka 51
SAMBA для 1С
Представлен необходимый минимум настройки SAMBA для работы файловых баз 1С через общий ресурс.
24.12.2021 4291 compil7 6
Регламентное задание по завершению сеансов пользователей 1С
Завершить работу пользователей в 1С ночью. Регламентное завершение работы.
06.12.2021 2448 Swamt 20
Базовые приемы работы с кластером 1С при помощи БСП
В данной публикации я рассматриваю базовые приемы работы с кластером серверных баз 1С, используя типовые типовые возможности библиотеки стандартных подсистем (БСП).
Источник