what are the possible reasons for 'Arithmetic overflow error converting expression to data type int' in SQL server
-
08-10-2020 - |
Question
When this command is run, there is SQL server error
'Arithmetic overflow error converting expression to data type int'.
SELECT sum(size) FROM [dbname]..sysfiles sf, [dbname]..sysfilegroups sfg WHERE sfg.groupname = 'PRIMARY' AND sf.groupid = sfg.groupid
Because the file size is less than 16TB, bigint
is not required. Still I tried to execute cast(size as bigint
), the error persists.
SELECT sum(cast(size as bigint)) FROM [dbname]..sysfiles sf, [dbname]..sysfilegroups sfg WHERE sfg.groupname = 'PRIMARY' AND sf.groupid = sfg.groupid
So the question is, what are the reasons for arithmetic overflow error other than exceeding the file size limit of 16TB.
Solution
-- casting using DECIMAL(38,2) throws exception, Size needs to be casted as bigint
select [SizeInMB] = CAST( ((SUM(Size)* 8) / 1024.0) AS DECIMAL(38,2) ) from sys.master_files
-- This fix is sufficient, but cannot limit to 2 decimal digits
select [SizeInMB1] = ((SUM(CAST(Size AS BIGINT))* 8) / 1024.0) from sys.master_files
-- 2 decimal digits are not available in fix, as divide by 1024.0 converts to default 6 digits
select [SizeInMB2] = ((SUM(CAST(Size AS DECIMAL(38,2)))* 8) / 1024.0) from sys.master_files
-- so 2 casts are required to eliminate Arithmetic overflow exception and limiting 2 decimal digits
select [SizeInMB3] = CAST( ((SUM(CAST(Size AS BIGINT))* 8) / 1024.0) AS DECIMAL(38,2) ) from sys.master_files