By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,574 Members | 1,968 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,574 IT Pros & Developers. It's quick & easy.

execute formula stored as string

P: 3
I have got a column in my table which stores mathematical formulas as strings. The base question is how do I evaluate the "string formula" to get result?

For example, I got a value like '2*5+2*5*4'.
I need a way to evaluate this string within an SQL Server stored procedure to get the result as 50

Declare @weight as string
Declare @output as numeric(18,2)

SET @weight = '2*5+2*5*4'.

Set @output = somefunction(@weight)

OutPut should be 50.

Thanks in advance for your help
Oct 20 '08 #1
Share this Question
Share on Google+
1 Reply


ck9663
Expert 2.5K+
P: 2,878
Two ways:

1. Use sp_executesql and use it's ability to return a parameter.


2. Take the long way:

Expand|Select|Wrap|Line Numbers
  1. declare @strFormula varchar(150), @intLength int, @inWidth int, @intHeight int, @intResult int
  2.  
  3. set @strFormula = 
  4.     '
  5.     declare @FormulaResult int
  6.     set @FormulaResult = [Length] * [Width] * [Height]
  7.     select @FormulaResult as FormulaResult
  8.     '
  9.  
  10. select  @intLength = 2, @inWidth = 5, @intHeight = 3
  11.  
  12. set @strFormula = replace(replace(REPLACE(@strFormula,'[Length]',cast(@intLength as varchar(3))),'[Width]', cast(@inWidth as varchar(3))),'[Height]',CAST(@intHeight as varchar(3)))
  13.  
  14. select @strFormula as strFormula
  15.  
  16. exec  (@strFormula)
  17.  
  18.  
Good luck!

-- CK
Oct 21 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.