How to CAST an INT data type as a BIGINT data type?

17.3k Views Asked by At

Someone suggested that the reason I get an error

Arithmetic overflow error converting nvarchar to data type numeric

when running some code is because I need to convert the INT data type of one of my variables to a BIGINT data type.

Does anyone know how to do this? I've tried the code below, but it didn't work!

TIA

    select
    es.ClientProductID,
    es.ProductName,
    ash.sales,
    CAST(ash.sales AS BIGINT) * CAST(ash.price as BIGINT) AS CashSales,
    ash.price,
    ash.cost,
    ash.date
from AggregatedSalesHistory as ash
join v_EnterpriseStructure as es on es.ProductSID = ash.ProductSID
join PriceZone as pz on pz.PriceZoneID = ash.PriceZoneID 

where 
    es.DepartmentName = 'Dairy' 
    and ash.segmentid = 0
    and pz.Name = 'South' 
    and ash.date >= '2014-1-1' and ash.Date<='2014-12-24'
    and (es.ClientProductID = 7119508806 
    or es.ClientProductID = 7119502372 
    or es.ClientProductID = 7003836538 
    or es.ClientProductID = 7119502437
    or es.ClientProductID = 2500002694
    or es.ClientProductID = 2500002606
    or es.ClientProductID = 7003836540
    or es.ClientProductID = 2500005433
    or es.ClientProductID = 2500005542
    or es.ClientProductID = 2500002893);
2

There are 2 best solutions below

1
On

Multiplying two ints will result in an int, at which point your result will already overflow. You should perform the casting before the multiplication:

CAST(ash.sales AS BIGINT) * CAST(ash.price as BIGINT) AS CashSales
1
On

You're missing a left paren.

CAST(ash.sales * ash.price) as BIGINT) AS CashSales, should be

CAST((ash.sales * ash.price) as BIGINT) AS CashSales,

Arithmetic overflow error converting nvarchar to data type numeric

Also, one of your fields is not numeric. You didn't post the structure so I can't tell which one.