Search This Blog

Wednesday, February 8, 2012

Interesting SQL Arithmetic overflow error problem

Hit an interesting SQL problem:
There were a number of int and numeric fields being converted to varchar() fields migrating data from System2 to System1.  I eliminated the obvious fields and hadn't solved it.  There were a number of columns with NULL values - one in particular: StandardTurnAroundTime


Cause:
 INSERT INTO SYSTEM1.dbo.W_EXAM (Exam_Duration_Tm)
SELECT StandardTurnAroundTime
FROM SYSTEM2.[dbo]. tbProcedures

Exam_Duration_Tm – varchar(4)
StandardTurnAroundTime –numeric(5.2) – max value 999.99 would cause Arithmetic overflow error
Turns out NULL value as tbProcedures. StandardTurnAroundTime was causing the issue.

Fix:
       CONVERT( varchar(4),CONVERT(int,ISNULL(StandardTurnAroundTime,0)))

INSERT INTO  SYSTEM1 .dbo.W_EXAM (Exam_Duration_Tm)
SELECT CONVERT( varchar(4),CONVERT(int,ISNULL(StandardTurnAroundTime,0)))
FROM  SYSTEM2 .[dbo]. tbProcedures
Returns values that will fit varchar(4) field even for values at the max of numeric(5,2) 999.99.

I was careful to test maximum values for numeric(5.2) to be converted to varchar(4).
How many times this would have been caught by manual code review?  


No comments: