Convert varchar to decimal - arithmetic overflow

I'm using SQL Server 2014 and I'm trying to convert data from a staging table over to a production table. I seem to be getting an Arithmetic overflow error converting varchar to numeric on the decimal conversion. I'm sure I've overlooked something with the
syntax of the CONVERT.
This is the staging table:
CREATE TABLE [dbo].[staging_table](
[TimeIndex] [varchar](100) NULL,
[Cluster] [varchar](100) NULL,
[AvgMem] [varchar](100) NULL,
[AvgCPU] [varchar](100) NULL,
[TotalMemory] [varchar](100) NULL,
[TotalCPU] [varchar](100) NULL,
[Datacenter] [varchar](100) NULL,
[vCenter] [varchar](100) NULL
) ON [PRIMARY]
This is the prod table I'm moving it to:
CREATE TABLE [dbo].[Clusters](
[ClusterID] [int] IDENTITY(1,1) NOT NULL,
[ClusterName] [varchar](25) NULL,
[DatacenterName] [varchar](25) NULL,
[TimeIndex] [datetime] NULL,
[AvgCPU] [decimal](5, 2) NULL,
[AvgMem] [decimal](5, 2) NULL,
[TotalCPU] [decimal](8, 2) NULL,
[TotalMem] [decimal](8, 2) NULL,
[vCenterID] [int] NULL,
CONSTRAINT [PK_Clusters_1] PRIMARY KEY CLUSTERED
[ClusterID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
and here's an example INSERT INTO statement throwing the error:
INSERT INTO [dbo].[Clusters] (ClusterName,DatacenterName,TimeIndex,AvgCPU,AvgMem,TotalCPU,TotalMem,vCenterID)
SELECT SUBSTRING(Cluster,1,25) AS ClusterName,
SUBSTRING(Datacenter,1,25) AS DatacenterName,
CONVERT(datetime,TimeIndex,103) AS TimeIndex,
CONVERT(decimal(5,2),AvgCPU) AS AvgCPU,
CONVERT(decimal(5,2),AvgMem) AS AvgMem,
CONVERT(decimal(8,2),TotalCPU) AS TotalCPU,
CONVERT(decimal(8,2),TotalMemory) AS TotalMem,
'3' FROM [dbo].[staging_table]
Sample data is 0.00 to 100.00 in fields AvgCPU and AvgMem, and TotalCPU and TotalMem usually goes up to about 7 digits with no decimal (eg. 7543253) but could be 8 and although I've never seen a decimal I wouldn't rule it out so decided to account for it.
I assume it's something I've overlooked with the syntax but any ideas would help.
Thanks
Adam

The problem is your precision and scale you are assigning to your decimals.
decimal(5,2) = this is a total of 5 digits, 3 digits for the whole number and 2 for the fractional.
decimal(8,2) = this is a total of 8 digits, 6 digits for the whole number and 2 for the fractional. 
So converting a varchar of 7 or 8 digits for TotalCPU or TotalMem will give you an error because your definition will actually only allow for 6 digits of storage. You could test this by doing decimal(8,0) or decimal(10,2) both which will allow for up to
8 whole numbers.
If you are worried about space Sql Server will allocate a set number of bytes for ranges based on the precision (first number in the parenthesis). See this page which explains in detail how much space each range takes up and also further details on
decimal and numerics.
-Igor

Similar Messages

  • Replace and convert varchar to decimal

    Hi all
    What could be the easiest way to replace and convert varchar(50) to decimal
    My string   '21 807,00'  Need to have it in db as  21807.00
    Thanks
    AKE

    On any version you can use somple convert with replace:
    declare @MyStr varchar(10) = '21 807,00'
    SELECT CONVERT(decimal(10,2), REPLACE(REPLACE(@MyStr, ',','.'),' ',''))
    but if there is a different format and the convert will not work, then you will get error. Therefore it is best (as mentioned) to use TRY_CONVERT on newer server or use Try block on old servers
    [Personal Site] [Blog] [Facebook]

  • Convert varchar to decimal in insert statement

    Hi i need one help from you.
    can you please help me out
    I have one insert statement where i am inserting some values.
    first when i am inserting the values are fetched from 'xml' file...
    so in one of the xml file i have 'varchar' values which i need to convert to decimal and i need to insert.
    from the below script i need this conversion for "M.Item.query('./unitPrice').value('0.0','decimal(18,2)') unitPrice"
    could you suggest me on this.
    INSERT INTO BWBLineItemDetails_New(Transaction_GUID,Transaction_ID,LineItemNumber,Quantity,UnitPrice,ProductCode,Ship_From_Addr,Ship_To_Addr)
            SELECT
            @Transaction_GUID,
            @TransactionId,
             M.Item.query('./lineItemNumber').value('.','int') lineItemNumber,
              M.Item.query('./quantity').value('.','int') quantity,
              M.Item.query('./unitPrice').value('0.0','decimal(18,2)') unitPrice,
              M.Item.query('./unitPrice').value('.','decimal') unitPrice,
              M.Item.query('./productCode').value('.','nvarchar(100)') productCode,
              M.Item.query('./shipFromAddress/address1').value('.','nvarchar(255)') + '' +  M.Item.query('./shipFromAddress/address2').value('.','nvarchar(255)')shipFromAddress,
              M.Item.query('./shipToAddress/address1').value('.','nvarchar(255)') + '' +  M.Item.query('./shipToAddress/address2').value('.','nvarchar(255)')shipToAddressEdited by: 891933 on Dec 4, 2012 5:27 AM

    If this was Oracle, I would point you at the to_number function, but since you seem to be using MS Sql Server, I suggest you ask in a Microsoft soecufic forum.
    This is the forum for Oracle's SQL Developer tool.

  • CAST Not working for me - Arithmetic overflow error converting int to data type numeric - error

    GPM is DECIMAL(5,2)
    PRICE is DECIMAL(11,4)
    COST is DECIMAL(7,2)
    Trying to update the Gross Profit Margin % field and I keep getting the "Arithmetic overflow error converting int to data type numeric" error.
    UPDATE SMEMODETAIL SET SMD_GPM = (SMD_PRICE-SMD_COST) / SMD_PRICE * 100
    FROM SMEMODETAIL WHERE SMD_PRICE<>0 AND SMD_QUANTITY<>0
    Example record:
    SMD_PRICE    SMD_COST    GPM%
    1.8500            1.62                12.4324324324324300
    I added cast and I still get the error.
    How do I format to get this to work?
    Thanks!

    Hi GBerthume,
    The error is caused by some value such as 1000.01 of the expression (SMD_PRICE-SMD_COST) / SMD_PRICE * 100 exceeds the
    precision of the column(DECIMAL(5,2)). The example data doesn't cause the overflow error for the value of the expression is 12.43 which is in the scope of DECIMAL(5,2).
    USE TestDB
    CREATE TABLE SMEMODETAIL
    SMD_PRICE DECIMAL(11,4),
    SMD_COST DECIMAL(7,2),
    SMD_GPM DECIMAL(5,2)
    INSERT INTO SMEMODETAIL(SMD_PRICE,SMD_COST) SELECT 1.8500,1.62
    UPDATE SMEMODETAIL SET SMD_GPM = (SMD_PRICE-SMD_COST) / SMD_PRICE * 100
    FROM SMEMODETAIL WHERE SMD_PRICE<>0-- AND SMD_QUANTITY<>0
    SELECT * FROM SMEMODETAIL
    DROP TABLE SMEMODETAIL
    The solution of your case can be either scale the DECIMAL(5,2) or follow the suggestion in Scott_morris-ga's to check and fix your data.
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

  • Arithmetic Overflow error converting float to data type numeric

    Hi,
    Am facing strange issue,I have function which returns money datatype and assigning the return money value to float datatype in table.
    Error msg:
    Msg 8115, Level 16, State 6, Procedure GBCalcCatalogPriceNewV2, Line 204
    Arithmetic overflow error converting float to data type numeric.
    The statement has been terminated.
    Strange thing is the same stored procedure is working fine in production environment,but in the deveopment i see this error.Am scared if the same happens in the production environment.Please advice and advance
    thanks
    Regards
    RAj

    Strange thing is the same stored procedure is working fine in production environment,
    How could that be strange? This is an error that occurs depending on the data. Accidents that are waiting to happen will happen sooner or later.
    Then again, a development database may be more prone to such errors, because data that entered are completely out of whack with real life data. Still it is a warning sign. If you have some place where you convert data from float to numeric, you must consider
    the risk that the float value is outside the range for the numeric data type. How do you prevent that from happening? Maybe a CHECK constraint on the column? Of if the data origins from a money column, use a numeric data type with sufficient precision.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Convert hh:mm varchar to decimal

    How do I convert varchar hh:mm (127:15) to a decimal (127.25)?
    Jeff

    <strike>
    may be just replace
    with t as (select '127:15' str from dual)
    select to_number(replace(str,':','.')) val
      from t</strike>
    Edited by: Karthick_Arp on Feb 15, 2010 7:43 AM
    my bad. dint read the OP properly. thanks to Massimo Ruocchio for pointing it out.

  • Arithmetic overflow error converting expression to data type int

    Hi
        iam creating on sp for  the  database total size , used mb and  free size .  percentage free . 
     in  this purpose i was creating on sps, with in the sp iam was writing  one select statement . it  statement is    
    SELECT [Drivename] ,[DataSizedUsedMB],[DriveFreeSizeMB],DriveTotalSizeMB,
      CAST( (DriveFreeSizeMB/DriveTotalSizeMB)*  100 AS NUMERIC(5,2))
       As
      [PercentFree] ,[DateRecorded] FROM 
    SELECT SUBSTRING([physical_name],1,1) AS Drivename,
      CAST(((SUM(COALESCE(size,0)))*8)/1024 AS NUMERIC(20,2)) AS DriveTotalSizeMB,
      CAST(((SUM( COALESCE( FILEPROPERTY( [name],'SpaceUsed'),0)))*8)/1024 AS NUMERIC(20,2)) AS DataSizedUsedMB,
      CAST(((SUM(COALESCE(size,0))-SUM(COALESCE(fileproperty([name],'spaceused'),0)))*8/1024)AS NUMERIC(20,2)) AS DriveFreeSizeMB
      ,SYSDATETIME()  AS [DateRecorded]
    FROM sys.master_files 
    GROUP BY SUBSTRING([physical_name],1,1))  AS Data
      it was executive one  server with out error  but the same select  statement is writing antoher server iam geeting  belo error.
    "@ErrorDesc: Line 24 - Line 13- Arithmetic overflow error converting expression to data type int." 
      how to slove this issue..
    please help me...

    Change 8 to 8E0, to make it a float literal. The data type of
    SUM(COALESCE(size,0)))*8)
    is int, since all components are int, and it can easily overflow the size for an int. If you use 8E0, you get a float, and the entire expression will be float.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Arithmetic overflow error converting expression to data type int. Why in this case?

    Hi guys, it is Friday and I am really tired but..
    WITH CTE AS (
    SELECT LEN(CONS_ID) AS PROCA FROM TryCons)
    SELECT SUM(PROCA) FROM CTE
    Why I retrieve
    Arithmetic overflow error converting expression to data type int.
    Len should returns a number and so sum should work. It can be because I am trying to read  500 millions rows? But it wouldn't make sense.. 

    Len should returns a number and so sum should work. It can be because I am trying to read  500 millions rows? But it wouldn't make sense.. 
    If the average length of the field exceeds 4.29, that statement will explode. Since I don't know what's in CONS_ID, I can't say whether it makes sense or not. Although, I will have to say that from my uninitiated position, this seems like an
    accident to happen.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Arithmetic overflow error

    Hi all,
    The below is suppose to generate random dates but I receive the following error:
    Msg 8115, Level 16, State 2, Line 7
    Arithmetic overflow error converting expression to data type datetime.
    SQL Below - if is this happening?
    DECLARE
    @MinDate INT, @MaxDate INT;
    DECLARE
     @RANGE INT = DATEDIFF(DD, @MinDate, @MaxDate);
    SET @MaxDate =20141212
    SET @MinDate = 20140101
    SELECT CONVERT(DATE, DATEADD(DD, ROUND(RAND(CAST(NEWID() AS VARBINARY)) * @RANGE,0,-1), @MinDate));

    Reason is because you've declared variable as int. An integer value of 0 represents a base date of 19000101. SO maximum possible integer value you can convert to date is 2958463 which is why it throws error for values 20141212,20140101
    etc
    convert them to string and they all work fine
    DECLARE
    @MinDate INT, @MaxDate INT;
    SET @MaxDate =20141212
    SET @MinDate = 20140101
    DECLARE
    @RANGE INT = DATEDIFF(DD,CAST( @MinDate AS varchar(8)), CAST(@MaxDate AS varchar(8)));
    SELECT CONVERT(DATE, DATEADD(DD, ROUND(RAND(CAST(NEWID() AS VARBINARY)) * @RANGE,0,-1), CAST(@MinDate AS varchar(8))));
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • 0FI_AR_4 Arithmetic overflow while extracting delta

    Hi All,
    While extracting 0FI_AR_4 delta from R/3 only data packages 2-4 were recieved in BW. Data package 1 is missing and the load was terminated with an error: "Arithmetic overflow error converting numeric to data type numeric.#3621 The statement has been terminated."
    Looking in RSA7 (in R/3 side) I can see all delta data waiting for Delta Repetition but can not locate any erroneous record (although I get "overflow" error when trying to sum one of the fields there. Sorting this field's values reveals nothing odd).
    Any idea as how to locate the bad record(s) , and as how to fix the problem?
    Thanks,
    OM

    Thank you Srinivas,
    I've checked ST22 log but besides listing the cause of the dump (Arithmetic overflow...) it gives no details as to the specific record / value / string.
    OM

  • Simple Round call results in Arithmetic overflow

    Hi,
    I'm a bit dazzled why this statement won't work in T-SQL : Select Round(9.990000, 0)
    The error I get is : Arithmetic overflow error converting expression to data type numeric.
    The result should be : 10
    I've tried this in SQL 2005,2008 and 2008 R2 (Error message if from R2), didn't find anything in BOL either
    Select ROUND(19.99, 0) works just fine
    Is this a bug or not? We develop accounting software and for us this is a dangerous bug.

    I can't be certain here, never having come across it before but I suspect that the number must have the same length in the "integer" part when you use ROUND like that.
    E.G. This works, giving "10" because the type is declared for the number.
    DECLARE @TEST AS FLOAT
    SET @TEST = 9.990000
    SELECT @TEST,Round(@TEST, 0)
    Whereas all of these fail
    SELECT Round(9.990000, 0)
    SELECT Round(99.990000, 0)
    SELECT Round(999.990000, 0)
    Do I make any sense here? :-)

  • Convert varchar(255) to varchar(50)

    I want to transfer data from a staging table to another table. The staging table has columns with datatypes I don't always want, and I'm converting them like so:
    INSERT INTO [dbo].[my_table]
    SELECT CONVERT(datetime,TimeIndex,103),
    CONVERT(decimal(6,3),Network_In,3),
    CONVERT(decimal(6,3),Network_Out,3),
    CONVERT(decimal(6,3),Network_Total,3)
    FROM [dbo].[staging_table]
    How would I convert varchar(255) to varchar(50)?
    Thanks in advance
    Adam

    Using substring is returning the column so thanks but now I can't convert datetime for some reason:
    INSERT INTO [dbo].[mytable]
    SELECT SUBSTRING(ClusterName,1,50) AS 'ClusterName',
    CONVERT(datetime,TimeIndex,103),
    ClusterID,
    CONVERT(decimal(3,2),Memory,3),
    CONVERT(decimal(3,2),CPU,3),
    CONVERT(int,CPUTotal),
    CONVERT(int,MemoryTotal)
    FROM [dbo].[stagingtable]
    GO
    Now I get an error I didn't get before:
    Implicit conversion from data type datetime to decimal is not allowed. Use the CONVERT function to run this query.
    But if I run the datetime convert on it's own as a single column select then it works okay. Any ideas where I've gone wrong there?
    To sum up - the above fails but the below works:
    SELECT CONVERT(datetime,TimeIndex,103) AS 'TimeIndex'
    FROM [dbo].[stagingtable]
    Thanks
    Adam

  • MBVOutPut Error PopulateFromRecordset, Err msg :Arithmetic overflow error

    Hi all
    We are experiencing technical difficulties. ie We have an Orchestration based Web Service,
    That sporadically consumes  lots of Memory.
    An Initial Analysis with Message Box Viewer.. Shows the following msg below.
    Any idea how one, can Interpret the message, locate and fix it?
    Thank in Advance
    ERROR : PopulateFromRecordset, Err msg :Arithmetic overflow error
    converting int to data type numeric. (STAGE : Executing SQL Query)
    MSGBOX DB 1 (MASTER) "BizTalkMsgBoxDb" on zx1000\BizTalkServer
    Col1
    NULL
    1 Rows
    AKE

    Here is part of the scenario.
    Type: = WCF-Basic-Http
    SOAP Action Header
    <BtsActionMapping xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" mlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Operation Name="StartInsertBizTalk" Action="http://schemas.myOpertion.com/StartInsertBizTalk" />
    Request response via Web Service
    Send Pipeline = XMLTransmit
    ReceivePipeline = XMLReceive.
    The Orchestration sends message
    We receives a response.. However, as soon as the response arrive.
    The message hangs and the process start consuming up to  8 Gig of memory.
    Hope it helps
    AKE

  • VARCHAR TO DECIMAL

    How can I conver this to a decimal
    Query :Convert(varchar(5),[ICD-9-CM]) as [ICD-9-CM]
    Current results: 4516
    I need character length of 5   ##.##
    YFLORES

    You can do as below. But Is it always 4 length character? Whats the purpose of doing?Can you explain in detail?
    Create table complete_Items([ICD-9-CM] varchar(2000))
    Insert into complete_Items Select '4516'
    Select Left(Convert(varchar(5),[ICD-9-CM]) ,2)+'.'+Right(Convert(varchar(5),[ICD-9-CM]),2)
    From complete_Items
    Drop table complete_Items

  • SQL 8115 : Arithmetic overflow error when running index analysis

    Hi experts,
      I got an error: "SQL 8115 : Arithmetic overflow error converting float to data type numeric
    row 1, col -1 [WP3 ] [sap_index_recommend:BUILD_N_E", please help.

    Hi João,
      It has been done.

Maybe you are looking for

  • Using external NAS drive for Time Machine and multiple Macs

    I just installed an external NAS drive from OWC's sister company Newer Tech. It is 500g with ethernet and usb2.0 connections. It works very well with easy setup with Time Machine with no hassle. However, in very fine print that I missed in the ad, it

  • How to get tapered brushes in cs5 photoshop

    Hi, I have cs5 photoshop and it seems to have a very limited amount of brush styles. Other people with cs5 have a large range of standard styles. I am just after the standard tapered end brush (tapered on both ends) Cheers

  • When I sent to Motion, it cut a second off of my clip????

    Hi all, I sent a 36 second clip from Final Cut 6 to Motion 3 and after putting in some text I returned to Final Cut and found that my clip was short (35 seconds) on the front and back end? Can anybody explain why that happened? Thanks

  • Pole-to-po​le telephone cable damage needs reporting.

    The telephone cable between two poles is missing the cover for the wiring connection. The cover was lying in the road. It was a "Western Electric" label, is thick black plastic, about 2 feet long and 6 inches in diameter. There is one of these about

  • Project titles in j2ee

    I m in need of some project titles in j2ee.can anybody help me plzzzzzzz