• steve.laforge (10/30/2012)


    I want to be able to pass a string and have it perform the equation within the string. For example, if I pass it "(7 + 1) / 3)", I owuld expect to get back 2.67.

    I have seen several posts on here, but none of them appear to work. So I attempted to create one myself. This is what I have in my stringEval function:

    Partial Public Class UserDefinedFunctions

    <Microsoft.SqlServer.Server.SqlFunction()> _

    Public Shared Function stringEval(ByVal equation As String) As SqlDecimal

    Dim table As New DataTable

    Dim eqObject As Object

    eqObject = table.Compute(equation, "")

    Dim results As SqlDecimal = SqlDecimal.Parse(eqObject.ToString())

    Return results

    End Function

    End Class

    I then try to test it with the following query:

    declare @results decimal(18,2)

    select @results = dbo.stringEval('(7 + 1) / 3')

    select @results as results

    When I run this in debug mode in VS2010, I see that the variable 'results' contains 2.6666666667 when it gets to the return statement. However, the query returns '3.00'. I feel like I am so very close to what everyone is asking for, but nobody seems to have an answer for.

    Can anyone help me resolve this?

    Many thanks!

    P.S., yes I know that this is VB instead of C#. I started my effort thinking that I could use the VB Eval function, but then realized that went away with VB.Net.

    What do you get whe you execute the following?

    declare @results decimal(18,2)

    select @results = dbo.stringEval('0.0+(7 + 1) / 3')

    select @results as results

    Also, why is someone after you to turn SQL Server into a calculator?

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)