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]

Similar Messages

  • 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

  • Checking and Converting binary, octal, decimal, and hex

    Hi,
    I have a classroom project which will need to validate that data entered in a text is of a certain type with a keyListener, and then convert that value to the other 3 types.
    I know character.isDigit will handle the decimal case, and that I can then use Integer.otString methods to convert to binary, octal, and hex, but what about the other cases?
    Thanks

    OK, this isn't working. If I've already established
    that the string entered into, for example, the
    integer-only textfield is a valid integer, I should be
    able to simply use integer.parseint(s, 2) to convert
    it into binary, right?Not exactly. You should be able to use Integer.parseInt(s, 2) to return the result of converting it from binary representation. You appear to think that this affects whatever "s" refers to, which is not the case. Note also, that method returns an int which is the decimal value in question.
    When you are thinking of int variables, be careful not to think of them as "decimal" or "binary". They are neither. They are just numbers. "Decimal" and "binary" are text representations of numbers, so those concepts can only be applied to strings.
    Integer.parseInt(s, 2);
    txtBin.setText(s);So here you want to assume that the input is a string that represents a number in decimal, and you want to find the string that represents the number in binary. Like this:// convert string in decimal representation to number
    int dec = Integer.parseInt(s);
    // convert int to binary representation as string:
    String binary = Integer.toBinaryString(dec);
    // write that to the text field
    txtBin.setText(binary);You could use a one-liner to do that, but you'll need the "dec" variable to set the other text boxes.
    Rembering why I hate OO...All of what I said there is true in just about all computer languages, OO or otherwise.
    PC²

  • 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.

  • Converting Binary to Decimal

    I would like to convert 12 and 32 digit strings into decimal. Is there
    a function in labview that does this? Does anyone have a vi (or sub-vi)?
    I'm using version 5.1
    Thanks!
    -DG
    [email protected]
    Sent via Deja.com
    http://www.deja.com/

    Hi Vinny,
    Thanks for the posting Vinny (and Stu). I did figure it out. The
    problem I initially had was that I had a 2-D array going into a for
    loop. I can break the array into 1-D arrays and then change this into
    an array into a string. No problems.
    Thanks!
    -DG
    In article <[email protected]>,
    vjrecca wrote:
    > hmmm, now I don't understand the question, because scan from string
    with a
    > %b format surely does take a string like "101101101110" and convert
    it to
    > decimal number 2926. Could you give a specific example of the string
    and
    > the expected result
    > - Vinny Recca.
    >
    > [email protected] wrote:
    >
    > > I've tried that, but to no success (I first convert the array into a
    > > sprea
    d sheet string, and then use the scan from string function.
    > >
    > > I did write a for while loop to do the conversion (basically using a
    > > shift register and putting the converted bits into an array that's
    > > built be the shift register, then adding them all up at the end).
    > >
    > > The numbers look off. Does Labiew intrinsically change the bits
    like
    > > from 0's to 1's when it's handling them?
    > >
    > > Thanks.
    > >
    > > -DG
    > >
    > > In article <_g3g6.76071$[email protected]>,
    > > "Stu McFarlane" wrote:
    > > > use the %b format string in the scan from string function (string
    > > functions)
    > > >
    > > > wrote in message news:95qec3
    > > $ekn$[email protected]..
    > > > > I would like to convert 12 and 32 digit strings into decimal. Is
    > > there
    > > > > a function in labview that does this? Does anyone have a vi (or
    sub-
    > > vi)?
    > > > >
    > > > > I'm using version 5.1
    > > > >
    > > > > Thanks!
    > > > >
    > > > > -DG
    > > > >
    > > > >
    [email protected]
    > > > >
    > > > >
    > > > > Sent via Deja.com
    > > > > http://www.deja.com/
    > > >
    > > >
    > >
    > > Sent via Deja.com
    > > http://www.deja.com/
    >
    >
    Sent via Deja.com
    http://www.deja.com/

  • 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.

  • I have a macbook, and i want to replace a processor and convert in macbook pro isthat possible , and wich processor is the best for my computer

    have a macbook, and i want to replace a processor and convert in macbook pro isthat possible , and wich processor is the best for my computer

    If you don't see any messages, not have anti-malware running or the Firewall on, try installing the Mac OS X 10.6.8 Update Combo
    It's ok to do this even though you are already running v10.6.8 (according to your profile).
    Restart your Mac after the combo in installed, try the App Store.
    Also... if you have an app called Little Snitch installed, that can prevent a connection to the App Store.

  • Convert hex to Decimal and keep leading zeros..

    Hi,
    I hope you can help?
    How to convert hex to Decimal and keep leading zeros
    I read 002C, hex, and I want to convert it to 0044 decimal.
    sscanf (MyNum, "%4x", &DecNum); will only give me 44.
    It have been working up till I started to get leading zeros.
    We will always have a 4 digit hex input in a range
    We must have the leading 00 in this case.
    How is this best done?
    Thanks for the help
    Simon
    Solved!
    Go to Solution.

    Hi,
    I don't really understand your problem. Is this stuff what you need ?
    int main (int argc, char *argv[])
    const char MyNum[] = "002C";
    int DecNum;
    sscanf (MyNum, "%4x", &DecNum);
    printf ("%04d", DecNum);
    getchar ();
    return 0;
    "0044" appears on standard output when printf function executes...

  • 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

  • Cast and convert

    Hi Team,
    could you please tell me where do we use cast and convert functions.
    What is the main difference between these two with examples.
    Thanks in advance.
    Mamatha

    I do remember using CAST when creating views with NULL values as columns (For some purpose it was required).
    If you dont use CAST when used null as column, the view column will be created as VARCHAR2(0). This will be an issue in some reporting tools.
    So using CATS you can change the data type to NUMBER or VARCHAR(50) (Example)
    SQL> create or replace view v1 as select null as col1 from dual;
    View created.
    SQL> desc v1
    Name                                      Null?    Type
    COL1                                               VARCHAR2
    SQL> create or replace view v1 as select cast(null as varchar2(50)) as  col1 from dual;
    View created.
    SQL> desc v1
    Name                                      Null?    Type
    COL1                                               VARCHAR2(50)CAST is also used with MULTISET, when working with OBJECT TYPEs..
    Read Here
    CONVERT is used when you want to see a particular text or column in a diffrent character set than the stored one. I have never used it , though...
    Edited by: jeneesh on Oct 12, 2012 6:05 PM

  • Long / double value convertion to Packed Decimal

    Hi,
    Could anybody tell me how to convert a long / double value to Packed Decimal (AS400) ?
    Thanks,
    Probir

    Now I'm writing this value in a flat file by
    FileOutputStream and sending to mainframe through FTP.
    But the mainframe people said it's not converted into
    packed decimal. Is it the right way to convert ??When you say "mainframe" I assume you are referring to a machine that uses EBCDIC. Java, even on the iSeries, uses Unicode and not EBCDIC, so when you FTP anything to the mainframe it will go through an ASCII-to-EBCDIC conversion. You want this to happen for text but you don't want it to happen for packed decimals; your carefully-constructed x'12' x'3f' bytes will be dutifully converted into EBCDIC garbage.
    FTP of an iSeries file (in the QSYS.LIB file system) to a mainframe is trivial because both client and server use EBCDIC, so there are no conversion issues. So if you could do it that way, you definitely should. Otherwise you are going to have to take your packed decimal data and replace it by the bytes that would be translated into it if it were in EBCDIC. The translation table QEBCDIC in library QSYS shows you how it does that, so use that table. You can look it with the command WRKTBL QSYS/QEBCDIC. You'll notice for example that x'09' in ASCII gets converted to x'05' in EBCDIC. So if you want to get x'05' into part of a packed decimal field on the mainframe, you have to send it x'09'. And so on. Like I said, I would recommend doing something other than this. Ask the mainframe people to not make you used packed decimal, for example.
    PC&#178;

  • I had to have my hard drive replaced, and I lost my Firefox Bookmarks. I don't know if I ever had a sync account or not. Is tehre a means to access my old bookmarks?

    My laptop hard drive crashed last week and I had to have it replaced. I had been using Firefox for about 18 months and had stored a number of GREAT websites for my career search. When I got my computer back from the shop, I had to reload all of my programs on the new hard drive. When I reloaded Firefox, t did not have my bookmarks, as i expected. The technicians that repaired my computer said that Firefox stores bookmarks remotely and i should be about to retrieve them. However, I never knew about the sync options. Hence, my guess is I am sunk. Any thoughts

    "I thought I saved my songs to DVD, however I have no clue how to retrieve them"
    Depending on whether you saved your files to DVD in folders or just as a group of files, put the DVD into your computer, open iTunes and go to Add folder to Library or Add File to Library. Navigate to the DVD and add your files back into iTunes: About the Add to Library, Import and Convert functions
    "now I try to disconnect my ipod from itunes it says it cannot be ejected as it contains files that are in use by another application"
    By any chance do you have McAfee ActiveScan or any other disk scanning software installed on on your PC? If so try switching it off before you eject.

  • Help converting binary to decimal.

    Hi all.
    I'm taking a course in Java programming and so far its been a great experience. I'm currently stumped on one of my assignments and I am kindly requesting some assistance.
    Basically I have to convert a binary entry into its decimal comparison.
    so for instance an entry of 1101 would output 13.
    I have the calculation formula, but my problem is finding out whether the point i'm looking at is either a 1 or a 0. I can't seem to 'strip it down' to the value.
    My current thought is something like this:
    binary = 1101;
    // problem is here
    thou = (binary % 1000) / 1000;
    hund = (thou % 100) / 100;
    tens = (hund % 10) / 10;
    ones = (tens % 1) / 1;
    // then do formular
    decimal = ones * 1 + tens * 2 + hund * 4 + thou * 8;
    I have searched but all the suggestions say to use a custom function or other obscure method. I don't know that stuff real well and we aren't even that far in the book either. All we've done so far is while, if .. else, condition statements.
    I will include the actual text for the question, in case i'm not clear. This text also includes a 'tip' which isn't helping me. (http://www.geocities.com/kaveman2000/q-4-25.pdf)
    Thanks again for any pointers.

    angeles1016 (and all),
    thanks for your great help and code snippets.
    angeles1016,
    using the code you provided i noticed that the last (single digit) was giving the wrong response in certain cases. (1000, 0111, 0001, ..) i could be off one.
    either way, i decided to fix it up and give you all the update.
    // do class, main function stuff
         if(binary/1000 == 1){
              thousands += (binary/1000);
         temp = binary % 1000;          
         if(temp/100 == 1){
              hundreds += (temp/100);
         temp = temp % 100;          
         if(temp/10 == 1){
              tens += (temp/10);
         temp = temp % 10;
         if(temp/1 == 1){
              ones += (temp/1);
         // calculate binary to decimal     
         decimal = (ones * 1) + (tens * 2) + (hundreds * 4) + (thousands * 8);
         // take result and convert to string for output
         result += "Decimal: " + decimal + "\n";
    // display in gui ?
    // end function and class stuff(note: i suppose the statements similar to "thousands += (binary/1000);" can be simplified as "thousands = 1;")

  • Convert varchar(20) date to date that looks like mm/dd/yyyy

    Good afternoon,
    I am a total novice at SQL and have been tasked to change a varchar(20) date column (shows up as m/dd/yy) to show up as mm/dd/yyyy. I've looked at the previous posts, but being a novice, it's difficult to wade through the non-applicable stuff. The column
    that needs to be changed is field2, but I'm not sure how to construct a statement to reflect my objective.
    Thank you in advance. 

    The sample uses a table variable. You can program it the same way for a table:
    DECLARE @t TABLE (dt VARCHAR(20))
    INSERT INTO @t
    VALUES ('1/2/12')
    ,('3/10/10')
    ,('7/23/9')
    ,('aa')
    ,('12/31/99')
    ,('10/20/00')
    ,('10/20/01')
    SET DATEFORMAT mdy
    SELECT dt
    ,CONVERT(VARCHAR(10), CASE
    WHEN isdate(dt) = 0
    THEN NULL
    ELSE cast(dt AS DATE)
    END, 101) AS newDt
    FROM @t;/******** TRY_CONVERT() method ************/
    SELECT dt, newDt=CONVERT(varchar(10),TRY_CONVERT(date,dt),101) FROM @t;
    GO
    dt newDt
    1/2/12 01/02/2012
    3/10/10 03/10/2010
    7/23/9 07/23/2009
    aa NULL
    12/31/99 12/31/1999
    10/20/00 10/20/2000
    10/20/01 10/20/2001
    dt newDt
    1/2/12 01/02/2012
    3/10/10 03/10/2010
    7/23/9 07/23/2009
    aa NULL
    12/31/99 12/31/1999
    10/20/00 10/20/2000
    10/20/01 10/20/2001
    Starting with SQL Server 2012 you can use TRY_CONVERT().
    You can start studying datetime functions here:
    http://www.sqlusa.com/bestpractices/datetimeconversion/
    Kalman Toth Database & OLAP Architect
    T-SQL Scripts at sqlusa.com
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Converting character to decimal format

    hi
    i am working on a development where the selection screen has date and time as select options.
    and based on the input i have to concatenate date and time into the format- DD.MM.YYY HH.MM.SS
    there is a value in the table that has a field containing the above value and i have to fetch the data based on this input.
    Now the problem is the field in the table is of format DECIMAL of 16 length.
    i want to know how can i pass this value to the select statement.
    thanks in advance

    Hi ,
    Please check the blog on the below link.
    [Re: Converting char to decimal value format as defined in SU3(User profile);
    This will solve your query.
    Regards
    Abhii......

Maybe you are looking for

  • Scheduling agreement pricing

    Hi, Pls tell me how the system will pick pricing in scheduling agreement. When i going to header condition system will give me message " Not possible to determine a condition type Message no. 06658 Diagnosis The system was not able to find a conditio

  • When installing Windows 7 using Bootcamp, expanding windows files gets stuck at 65%?

    I was installing Windows 7 Home Premium 64 bit on my Macboom Pro Retina with Bootcamp, and when it reached the "expanding windows files" stage, it got stuck at 0%. I waited a few minutes, and the percentage began to increase until it got to 65%, at w

  • Appletv only sees SOME tv shows

    My appletv sees tv shows purchased from the itunes store, but any thing I mark as a tv show that is a video file of my own does not show up. If I change it back to movie though, it is visible. Suggestions?

  • Vendor Evalution - Vendor Class

    Hi 1. What is the exact purpose of Vendor class ? How it can be used in Vendor Evaluation and other areas ? 2. Can we group some Vendors in to a Vendor class so that we can assign the Weighting key to the Vendor Class instead of Vendor by Vendor in V

  • How do I properly remove programs?

    This is a long story, so I'll give the short version... I was trying to update my Compressor software, but after I installed the update, it wouldn't open. I realized I had installed a version of compressor that needed OSX 10.4 or higher, I'm using 10