error when dividing Arithmetic overflow error converting int to data type numeric so how to solve it ?

ahmed salah 3,216 Reputation points
2022-03-01T15:46:23.927+00:00

i WORK ON SQL SERVER 2012 i face error
Msg 8115, Level 16, State 8, Line 1
Arithmetic overflow error converting int to data type numeric.
The statement has been terminated.

statment generate error

 select m.companyid,m.[Year],m.rev_id,CountMaterials,CountMaterialsConfirment,
FORMAT(case when c.CountMaterialsConfirment IS NULL then 0 ELSE cast(c.CountMaterialsConfirment as decimal(5,2)) / cast(m.CountMaterials as decimal(5,2))  END * 100,'N2')  as totalpercentage  
into ExtractReports.dbo.CountTotalPercentage
 from ExtractReports.dbo.CountDistinctMaterials m with(nolock)
 left join ExtractReports.dbo.CountDistinctMaterialsConfirments c with(nolock) on m.companyid=c.companyid and m.[year]=c.[year] and m.rev_id=c.rev_id

so how to solve issue please ?

Developer technologies Transact-SQL
SQL Server Other
{count} votes

3 answers

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2022-03-01T17:35:27.577+00:00

    Try decimal(35,2) instead of decimal(5,2).

    0 comments No comments

  2. Tom Phillips 17,771 Reputation points
    2022-03-01T18:05:54.823+00:00

    That error indicates " as decimal(5,2))" is not big enough for your number.

    Also, assuming they are both INT, you only need to cast one of them to decimal to get decimal places in the divide.


  3. LiHong-MSFT 10,056 Reputation points
    2022-03-02T06:28:37.477+00:00

    Hi @ahmed salah
    Check this:

    FORMAT(case when c.CountMaterialsConfirment IS NULL then 0 ELSE cast(c.CountMaterialsConfirment as float) / cast(m.CountMaterials as float)  END * 100,'N2')  as totalpercentage  
    

    Best regards,
    LiHong

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.