Question : Convert String to Mathematical Formula

I am trying to create a function so that one can input variables (Float) and a formula (Varchar) which may change from time to time. The function will use the variables within the given formula and return a result. The problem is that I can't convert the String formula to a mathematical function.....I tried extracting the quotes from the string and casting the Varchar but it doesn't help....Here is an extract example:
Declare @InputA Float
Declare @InputB Float
Declare@InputFormula Varchar (50)
Declare@Result Float

Set @InputA=1   --This will be passed into the function
Set @InputB=3   --This will be passed into the function
Set @InputFormula='@InputA+@InputB'  --Ultimately this will be passed into the function as a string
/* Tried The following
Set FormulaX=Replace(@InputFormula,"'","")  
Print FormulaX  -- got @InputA+@InputB   so got rid of the quotes..but not much help
-- Tried  Cast(@FormulaX as Float)  got an error... */

Select @Result=@FormulaX
Print @Result   --Expecting to See 4   best got was @InputA+@InputB

Any help will be appreciated...





Answer : Convert String to Mathematical Formula

note: I doubt that FLOAT is really the data type you want to use, as FLOAT is unprecise.
I suggest that unless you have a clear vision/understanding/requirement of that data type, you use DECIMAL(20,4) instead.

in regards to your question, the main problem will be how flexible the formula could be.
anyhow, you need the sp_executesql function
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
Declare @InputA decimal(20,4)
Declare @InputB decimal(20,4)
Declare @InputFormula nVarchar (500)
Declare @Result decimal(20,4) 
Set @InputA=1   --This will be passed into the function
Set @InputB=3   --This will be passed into the function
Set @InputFormula='@InputA+@InputB'  --Ultimately this will be passed into the function as a string 
/* here is the code */
Set @InputFormula = ' SELECT @res = ' + @InputFormula 
EXEC sp_executesql @inputFormula, N'@InputA decimal(20,4), @inputB decimal(20,4), @res decimal(20,4) OUTPUT ', @InputA, @inputB, @result OUTPUT 
Print @Result   --Expecting to See 4   
Open in New Window Select All
Random Solutions  
 
programming4us programming4us