SQL using a string table field as a formula to calculate results in decimal form

I have a table which contains a data field which is in VARCHAR format that contains a formula. I would like to convert that formula into a decimal value in a new data field.

This is what one of the fields looks like:

CommonPrograms.dbo.cp_GreaterUDF(.05,(CommonPrograms.dbo.cp_GreaterUDF(.0225,225*.01) + 125*.01)) + 4.5

"CommonPrograms.dbo.cp_GreaterUDF" is a user-defined function that calculates the greater of two numbers. But there could be anything in that field. For example: the data field could contain: 2+3+6*100

Could you please send me code that will convert the VARCHAR field into a decimal data field which will now reflect the results of the formula?


LVL 10
Who is Participating?
Guy Hengel [angelIII / a3]Billing EngineerCommented:
you would need to run that expression somehow dynamically, which means you can only do it one row by one.
with sp_executesql you could then fetch the results...

declare @sql nvarchar(max)
declare @result decimal(20,5)

set @sql = ' set @res = ' + 'CommonPrograms.dbo.cp_GreaterUDF(.05,(CommonPrograms.dbo.cp_GreaterUDF(.0225,225*.01) + 125*.01)) + 4.5 '
exec sp_executesql @sql, N'@res decimal(20,5) output', @result OUTPUT
select @result 

Open in new window

Try casting :

CAST (DataField AS DECIMAL (3, 2))
HainKurtSr. System AnalystCommented:
something like this may work
declare @CustId int32
  declare @Formula nvarchar(1000)
  declare @sql nvarchar(4000)
	declare CustList cursor for
	select custid, formula from myTable where ...

	OPEN CustList
	FETCH NEXT FROM CustList INTO @CustId, @Formula

	  set @sql='update myTable set colX=' + @formula +' where CustID=' + @CustID;
	  exec @sql;
	  FETCH NEXT FROM CustList INTO @CustId, @Formula

	CLOSE CustList

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.