Hi,
Is it possible to evaluate a varchar formula and calculate variable value i.e.
I have a formula saved in a varchar variable: (202/7.3 + 67) * 2 - 12 + 6+@param = 210.67
How can I get @param result
Thanks
Use the following query..
Declare @result as float; Declare @param as float; Set @param = 100 Exec sp_executesql N'Set @ReturnResult = (202/7.3 + 67) * 2 - 12 + 6 + @Inputparam' ,N'@Inputparam as float, @ReturnResult as float output' ,@param ,@result OUTPUT Select @result
Mani,
The result of your formula is 283.34, and the result of clintz formula is 27.33.
I think that there is no question that clintz's formula more closely parallels the OP needs -and that yours misses the mark on this one...
In order to solve the equation, the OP needs to revise the 'formula' so that it can be solved.
Try:
declare
@sql nvarchar(4000)declare
@param numeric(10, 4)
set
@sql = N'set @param = -1 * ((202/7.3 + 67) * 2 - 12 + 6 - 210.67)'
exec
sp_executesql @sql, N'@param numeric(10, 4) output', @param output
select
@param
AMB
Thanks Manivannan,
But what I need is reversed calculation, which mens that I have the @result, need @param to be output.
![]()
Bill
Hi Bill,
You can rearrange the formula in order to get @param. See my post.
AMB
Thanks everyone,
In my case, the formulas are user defined, they are totally dynamic and may be more complex, for example:
declare @formula varchar(MAX)
set @formula = ' (202/7.3 + 67) * 2 - (12 - (6 + @param*2))/7 = 210.67'
Bill
Hi Bill,
As I told you, you can rearrange the formula in order to get @param, like a math problem, right.
AMB
SQL Server isn't really a mathmatics library, at all. So there isn't a good way to evaluate:
(202/7.3 + 67) * 2 - 12 + 6+@param = 210.67
Using T-SQL. As everyone is trying to say, you can easily rewrite this as:
select
-1 *( (202/7.3 + 67) * 2 - 12 + 6 - 210.67) as [@param]
To get the answer. So however the formula is created, you could simply rearrange the query to move the variable out of the formula (as we all learned in Algebra, all those years ago.)
If your question is how can you do this with T-SQL with no work on your part, then you "could" do it with guessing.
declare
@param decimal(10,2)declare
@result decimal(10,2)
set
@param = 1select
@result = (202/7.3 + 67) * 2 - (12 - (6 + @param*2))/7select
@result
if
@result < 210.67set @param = @param - 2
else
set @param = @param + 2
select
@result = (202/7.3 + 67) * 2 - (12 - (6 + @param*2))/7
This would be a rediculous way of solving a problem, but you could do it ![]()
If you are stuck with this formula, you might look at .NET and see if there are libraries to do this sort of thing. It would be child's play to implement this using a CLR function if one existed.
Bill YU wrote:
You are correct, but how to evaluate it