467,910 Members | 1,772 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,910 developers. It's quick & easy.

execute formula stored as string

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
  • viewed: 8241
Share:
1 Reply
ck9663
Expert 2GB
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.

Similar topics

2 posts views Thread by Duane Phillips | last post: by
1 post views Thread by FireListen | last post: by
4 posts views Thread by Klaus Jensen | last post: by
1 post views Thread by Nishanth | last post: by
1 post views Thread by Karthik C | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.