Parse a calculation

  • I have 3 fields I am working woth from a table.

    2 are numbers, and one is text.

    A row for example may be:

    Num1: 20

    Num2: 10

    Text1: *

    I need to do the calculation Num1 Text1 Num2, or 20 * 10.

    SQL Server compalins if I try to cast "20 * 10" as a number of any type. How can I parse the calculation?

  • DECLARE @SQLStr VARCHAR(30)

    SELECT @SQLStr = CAST(Num1 As VARCHAR(10)) + Text1  + CAST(Num1 As VARCHAR(10))

    FROM A

    EXEC ('SELECT ' + @SQLStr)

    You may have to add this in a loop for all the records. I am not sure if this can be done for all the records in 1 query

     


    Kindest Regards,

    Amit Lohia

  • Mathew...you could do something like this:

    select Result = case

    when Text1 = '*' then (Num1 * Num2)

    when Text1 = '+' then (Num1 + Num2)

    when Text1 = '-' then (Num1 - Num2)

    when Text1 = '/' then (Num1 / Num2)

    end

    from myTable

    ..or you could add a "computed column" to your table with the same expression as the case statement - like so:

    create table tblParseCalcs
    (Num1 int,
    Num2 int,
    Text1 char(1),
    Result as case
    when Text1 = '*' then (Num1 * Num2)
    when Text1 = '+' then (Num1 + Num2) 
    when Text1 = '-' then (Num1 - Num2) 
    when Text1 = '/' then (Num1 / Num2)
    end)
    
    insert into tblParseCalcs values(20, 10, '*')
    insert into tblParseCalcs values(20, 10, '-')
    insert into tblParseCalcs values(20, 10, '+')
    insert into tblParseCalcs values(20, 10, '/')
    
    select * from tblParseCalcs
    
    2010*200
    2010-10
    2010+30
    2010/2
    
    







    **ASCII stupid question, get a stupid ANSI !!!**

  • Thanks for your help everyone. I'll test some of this out.

  • Check out the script section, a much more complete script could do all those operations and much more.

Viewing 5 posts - 1 through 4 (of 4 total)

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