- May 18, 2001
- 7,881
- 378
- 126
First off, I'm programming in Microsoft TSQL.
We have a table with a varchar field that contains mathematical formulas as strings. For example, the following would be a valid entry in this field:
"@var1 + @var2 / @var3" (NOTE THE QUOTES - THIS IS A STRING)
Some languages contain an "evaluate" function that allows something like the following:
SELECT @var1 = 1, @var2 = 2, @var3 = 3, @formula = "@var1 + @var2 / @var3"
SELECT evaluate(@formula)
The result of the code above would be that the formula stored in the string @formula would be evaluated using the variables that are named within the formula string.
To summarize, I need the ability to execute a formula that is 1) stored in a string, 2)not known until it is retrieved from a table, and 3) contains the names of variables that are already declared elsewhere in the function.
I suspect that there is an easy answer for this one, but I'll ask anyway: how do you do this in TSQL?
EDIT: Snapster has a nearly complete solution below, but now I've hit another snag. The line below doesn't work:
EXEC ('SELECT 5/2')
This line doesn't work because it always returns the truncation of the decimal answer (i.e. the example above returns 2). Does anyone have any suggestions?
We have a table with a varchar field that contains mathematical formulas as strings. For example, the following would be a valid entry in this field:
"@var1 + @var2 / @var3" (NOTE THE QUOTES - THIS IS A STRING)
Some languages contain an "evaluate" function that allows something like the following:
SELECT @var1 = 1, @var2 = 2, @var3 = 3, @formula = "@var1 + @var2 / @var3"
SELECT evaluate(@formula)
The result of the code above would be that the formula stored in the string @formula would be evaluated using the variables that are named within the formula string.
To summarize, I need the ability to execute a formula that is 1) stored in a string, 2)not known until it is retrieved from a table, and 3) contains the names of variables that are already declared elsewhere in the function.
I suspect that there is an easy answer for this one, but I'll ask anyway: how do you do this in TSQL?
EDIT: Snapster has a nearly complete solution below, but now I've hit another snag. The line below doesn't work:
EXEC ('SELECT 5/2')
This line doesn't work because it always returns the truncation of the decimal answer (i.e. the example above returns 2). Does anyone have any suggestions?