Dynamic Evaluation

  • I need to be able store a formula in a character (varchar) field or variable, execute the formula, and get back the result. For instance, if my variable is set to '(3*4)', I need to be able to pass the formula string to a function that will evaluate it and return the result (12). I have been able to do this in a stored procedure, but I can't figure out how to do it in a function. Has anyone done this, or know how to do it?

    Thanks.

  • It is not so easy.

    You have to make a parser (like lex and yacc).

    The basic idea is to search for the numbers and the operands.

    Here is the beginning what you have to evolve for your needs:

    declare @v-2 varchar(10)

    declare @n1 int, @n2 int, @op char(1), @pos int

    set @v-2 = '15+65'

    if charindex('*', @v-2) > 0

    begin

    set @pos = charindex('*', @v-2)

    set @op = '*'

    end

    if charindex('+', @v-2) > 0

    begin

    set @pos = charindex('+', @v-2)

    set @op = '+'

    end

    -- set other operands here

    -- ...

    if @pos > 0

    begin

    set @n1 = cast(left(@v, @pos-1) as int)

    set @n2 = cast(right(@v, len(@v)-@pos) as int)

    end

    select case when @op = '*' then @n1 * @n2

    when @op = '+' then @n1 + @n2

    -- set other operands here

    -- ...

    end

    Bye

    Gabor



    Bye
    Gabor

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply