Question

Convert varchar string to decimal

Asked by: kelvinsparks

Hi Experts

I have a SP that creates a varchar(200) string that creates from a table entry such as (A+(0.75*B)) a string such as (0.093000000000+(0.75*0.004087939911))

I now need to evaluate this string and store the resultant decimal value (0.096065948
)

I've tried the CAST statement as in CAST(@E as decimal(24,18)) where @E = (0.093000000000+(0.75*0.004087939911)) and get the error Server: Msg 8114, Level 16, State 5, Line 96
Error converting data type varchar to numeric.

A solution please

Thanks

Kelvin

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-10-09 at 21:14:56ID21589209
Tags

convert

,

decimal

,

varchar

,

string

Topic

MS SQL Server

Participating Experts
2
Points
500
Comments
15

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Convert from varchar to decimal
    hi all i have a field which is stored as a varchar(30). I need it as varchar as the value can be characters or numbers etc. in some case i need to add two of these fields when the text value are deciamls e.g. '.75' to do this i need to change them to decimals first. i hav...
  2. How to convert decimal to varchar
    Select OrderID, 'Sell--' + Convert(varchar(24), sum(CAST(Price AS DECIMAL(13,2))) ) From OrderDetail GroupBy OrderID I want to display price as varchar but somehow above code send an following error "Error converting data type varchar to numeric." I want to disp...
  3. cast varchar to decimal
    one field - varchar(10) - contains a whole bunch of this: 98.75 9803.00 98030.00 99.05 .71 .70 .00 i MUST cast as decimal asap. i tried this: cast(field as decimal(18,2)) it fails: error converting data type varchar to numeric i've checked the min/max/avg column ...
  4. cast one value from a varchar column to decimal (10,2…
    cast one value from a varchar column to decimal (10,2) using sql server
  5. Error Converting Varchar to Decimal Strange Behavior
    We have a database in a MS SQL 2005 SP1 server. We have a select statement that joins two tables and converts a field from table 2 from a varchar to a decimal. The field that is a varchar has only numbers in it and we have verified that using isnumeric(). Our select statem...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: dsinePosted on 2005-10-09 at 21:57:34ID: 15050153

CREATE  procedure calculate
      @strIDs VarChar(100)
AS
BEGIN
    DECLARE @i INT, @sql NVARCHAR(512)
 
    SET @sql = N'SELECT ' + @strIDs
 
    EXEC sp_executesql
        @query = @sql,
        @params = N'@i INT OUTPUT',
        @i = @i OUTPUT

    PRINT @i
END
GO


this should work... u can do this part in your orignal stored procedure returning the expression itself.

 

by: kelvinsparksPosted on 2005-10-10 at 01:40:43ID: 15050742

Thanks

I have added these lines to my SP

DECLARE @sql nvarchar(512)
SET @sql = N'SELECT ' + @E
EXEC sp_executesql @query = @sql,@params = N'@V decimal(24,18) OUTPUT', @V = @V OUTPUT
Print @V

@E has been previously set to (0.093000000000+(0.75*0.004087939911))

This error is returned
Server: Msg 8115, Level 16, State 8, Line 101
Arithmetic overflow error converting numeric to data type numeric.

 

by: dsinePosted on 2005-10-10 at 01:49:22ID: 15050766

what is the output variable definition that you have defined for you sp?

 

by: kelvinsparksPosted on 2005-10-10 at 01:52:32ID: 15050774

Getting a little out of my depth here. @V is a local variable of type decimal(24,18) - not set to output or anything special. I just wanbt to get the result of this numeric string to use later in my SP (will be used in an UPDATE statement a little later to update a value

 

by: dsinePosted on 2005-10-10 at 02:03:01ID: 15050822

ok can you paste the entire SP here.

 

by: kelvinsparksPosted on 2005-10-10 at 02:17:39ID: 15050894

A bit difficult to do that as there is a bit of functionality theat is not obvious from the SP and that works fine. I'll describe it to the point where it is OK, and copy in the part that is a problem.

We have a table where one of the fields holds a 'mask' for formulae in this case it is (A+(0.75*B)) - there can be up to three variables in the mask.

The values of A and B are retrieved from another table based on parameters and put into the mask which creates a varchar string which is @E in my SP. @E is decaled as varchar(200). In the example I have been testing
@E = (0.093000000000+(0.75*0.004087939911)) - I can get to this point successfully
I have declared another variable @V as decimal(24,18) - a high level of precision as this is used in a financial system calculating returns.

I need @V to be the evaluated value of @E, which in this case is 0.096065948 and it must be as a decimal as it will be APPENDED or UPDATED into a table of other returns.

AS advised earlier, I have edited your code and added it into my SP after the @E is finalised as follows
DECLARE @sql nvarchar(512)
SET @sql = N'SELECT ' + @E
EXEC sp_executesql @query = @sql,@params = N'@V decimal(24,18) OUTPUT', @V = @V OUTPUT
Print @V

I'm using the print, only because I'm testing using Query analyzer. A more typical use after resolving the equation would be

INSERT INTO [Index Returns] ([INDEX],[DATE],BENCH_1M, BENCH_UNIT)
VALUES (@Idx, @IRDate,@V,@d2*(1+@V))

 

by: dsinePosted on 2005-10-10 at 02:35:22ID: 15050973

OK the logic is clear to me.the reason that I requested the entire SP is that it helps me understand it better. I am sure that the rest of the SP is fine since u  were able to work it till now. Also can you point me to the 101 line after the new code was inserted.

 

by: kelvinsparksPosted on 2005-10-10 at 02:38:03ID: 15050987

Will get back to you. Have just cut part of it out into new query in QA and it seems to work. Will try to quickly nut it out, otherwise will post it for you to assist

 

by: kelvinsparksPosted on 2005-10-10 at 02:45:43ID: 15051010

Thios is the 'short' version of what I was attempting

DECLARE @E      varchar(200),
      @V      decimal(24,18),
      @sql      nvarchar(512)

SET @E = (0.093000000000+(0.75*0.004087939911))
PRINT @E
SET @sql = N'SELECT ' + @E
PRINT @sql
EXEC sp_executesql @query = @sql,@params = N'@V decimal(24,18) OUTPUT', @V = @V OUTPUT
print @V

When run in QA I get the following messages

0.09606595493325
SELECT 0.09606595493325

(1 row(s) affected)

Note @V did not return (presumably as it was an output variable in the EXEC statement. The correct value did show in the grid. I am most intrigued that @E was evaluated and that was printed. That is largely what I need. Next message will have my Original SP

 

by: kelvinsparksPosted on 2005-10-10 at 02:50:55ID: 15051035

This is orginal SP to the point of the problem

DECLARE       @IRIndex      varchar(70),
                  @IRDate            datetime,
                  @iCount            int,
                  @Idx            varchar(70),
                  @A            varchar(70),
                  @B            varchar(70),
                  @C            varchar(70),
                  @E            varchar(200),
                  @V            decimal(38,30),
                  @sql            nvarchar(512)

      SET @IRIndex = 'MSCI Emerging Markets Index (NZD)'
      print @IRIndex
      SET @IRDate = CONVERT(DATETIME, '2005-09-30 00:00:00', 102)
      print @IRDate
      SELECT @iCount = (SELECT COUNT([INDEX]) FROM [Index Combinations] WHERE [SOURCE INDEX A] = @IRIndex OR [SOURCE INDEX B] = @IRIndex OR [SOURCE INDEX C] = @IRIndex)
      print @icount

      IF @iCount = 0 GOTO ENDPROC

      DECLARE curIRC CURSOR LOCAL FAST_FORWARD
      FOR
      SELECT [INDEX], [SOURCE INDEX A],[SOURCE INDEX B],[SOURCE INDEX C],[EQUATION]
      FROM [Index Combinations]
      WHERE  [SOURCE INDEX A] = @IRIndex OR [SOURCE INDEX B] = @IRIndex OR [SOURCE INDEX C] = @IRIndex

      OPEN curIRC

      FETCH NEXT FROM curIRC
      INTO @Idx, @A, @B, @C, @E
      print @Idx
      print @A
      print @B
      print @C
      print @E

      WHILE @@FETCH_STATUS = 0
      BEGIN
            DECLARE @i1 int, @i2 int, @i3 int
            SET @i1 = (SELECT COUNT([INDEX]) FROM [Index Returns] WHERE [INDEX] = @A AND [DATE] = @IRDate)
            SET @i2 = (SELECT COUNT([INDEX]) FROM [Index Returns] WHERE [INDEX] = @B AND [DATE] = @IRDate)
            SET @i3 = (SELECT COUNT([INDEX]) FROM [Index Returns] WHERE [INDEX] = @C AND [DATE] = @IRDate)
            print @i1
            print @i2
            print @i3
            IF @i1 = 0 OR @i2 = 0 OR ( @C is not null and @i3 = 0)    -- This Index Return not yet available
                  BEGIN
                        GOTO EndEquation
                  END
            
            DECLARE @d1 decimal(12,12), @d2 decimal(12,12), @d3 decimal(12,6)
            SET @d1 = (SELECT BENCH_1M FROM [Index Returns] WHERE [INDEX] = @A AND [DATE] = @IRDate)
            print @d1
            SET @d2 = (SELECT BENCH_1M FROM [Index Returns] WHERE [INDEX] = @B AND [DATE] = @IRDate)
            print @d2
            SET @d3 = (SELECT BENCH_1M FROM [Index Returns] WHERE [INDEX] = @C AND [DATE] = @IRDate)
            print @d3
            IF @d1 IS NULL OR @d2 IS NULL OR (@C is not null and @d3 IS NULL) -- NULL value for Return
                  BEGIN
                        GOTO EndEquation
                  END

            --Replace "A" in equation with value
            print @E
            SET @E = REPLACE(@E,'A',@d1)
            print @E
            --Replace "B" in equation with value
            SET @E = REPLACE(@E,'B',@d2)
            print @E
            --Replace "C" in equation with value
            IF @i3 <> 0
            BEGIN
                  SET @E = REPLACE(@E,'C',@d3)
            END

            --Check for previous month data for this Index Combination
            SET @i1 = (SELECT COUNT([INDEX]) FROM [Index Returns] WHERE [INDEX] = @Idx AND [DATE] = dbo.DateAdder(@IRDate,-1))
            IF @i1 = 0
                  BEGIN
                        INSERT INTO [Index Returns] ([INDEX],[DATE],BENCH_UNIT)
                        VALUES (@Idx, dbo.DateAdder(@IRDate,-1),1)
                  END

            --Calculate the equation
            print @E
            SET @sql = N'SELECT ' + @E
            EXEC sp_executesql @query = @sql,@params = N'@V decimal(24,18) OUTPUT', @V = @V OUTPUT
            --SET @V = CONVERT(decimal(38,24),RTRIM(LTRIM(@E)))
            print @V

Now I find that this is working and returning the correct value to the grid. My error is coming from further down where I haven't looked yet. My problem is to grab that output value into the local variable @V so I can use it further on.

 

by: dsinePosted on 2005-10-10 at 03:00:58ID: 15051084

well you have already grabbed the value.. @V is the result and you may use it as any other variable that you have.

your variable v is defined as @V  decimal(38,30) at the start of the SP.. ther arithmetic overflow error can ocur if you are assigning any operation done on this number to a lower precision,scale variable. so you may like to go through your code to see if that is happening. And stick to the same definition for all numeric variables to reduce chances of overflows happening.



 

by: kelvinsparksPosted on 2005-10-10 at 03:46:51ID: 15051241

Not quite

If you look at the print statements from this simplified routine

DECLARE @E      varchar(200),
      @V      decimal(24,18),
      @sql      nvarchar(512)

SET @E = (0.093000000000+(0.75*0.004087939911))
SET @sql = N'SELECT ' + @E
EXEC sp_executesql @query = @sql,@params = N'@V decimal(24,18) OUTPUT', @V = @V OUTPUT
print 'V = '
print @V

The messages are

(1 row(s) affected)

V =

There is no printed value for @V. The value is in the grid, but how do I grab it for further use. @V appears to be NULL

 

by: dsinePosted on 2005-10-10 at 05:45:27ID: 15051770

ok i don;t know why what we did earlier does not work, maybe some other expert might throw some light on that..
meanwhile this works... I am shutting down for the day. catch up on this tomorrow. Best of luck


CREATE  procedure calculate
     @strIDs VarChar(100)
AS
BEGIN
    DECLARE @i decimal(24,18), @sql NVARCHAR(512)
    CREATE TABLE #result (calc decimal(24,18) NOT NULL)
    select @sql = N'SELECT ' + @strIDs
   INSERT into #result (calc)
      EXEC(@sql)
    set @i=(select top 1 calc from #result)
        select @i
END
GO

 

by: ScottPletcherPosted on 2005-10-10 at 08:06:00ID: 15052753

Just change the datatype in the dynamic SQL.


DECLARE @result DECIMAL(24, 18), @sql NVARCHAR(512)
 
SET @sql = N'SELECT ' + @E
 
EXEC sp_executeSql @sql, N'@result DECIMAL(24, 18) OUTPUT', @result OUTPUT

PRINT @result

 

by: ScottPletcherPosted on 2005-10-10 at 08:08:33ID: 15052777

This should work most of the time.  But with certain expressions I would think you might still have some conversion/overflow issues, since no CAST is done in the original expression.  That is, if instead of:

(0.093000000000+(0.75*0.004087939911))

You could somehow specify:

(CAST(0.093000000000 AS DECIMAL(24, 18))+(0.75*0.004087939911))

I think you would be completely safe.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...