I just created a table with 5 million rows. With a table structure like:
rn t1 t2 t3 formula 1 80 23 93 t1 / t2 * t3 2 80 87 30 t1 / t2 * t3 3 92 83 63 t1 / t2 * t3 4 68 19 36 t1 / t2 * t3 5 65 63 10 t1 / t2 * t3
If you are sure that all your formulas are valid and you will not have division by zero, for example, or data type overflows, in this case you can create your own eval () function on the SQL server.
I created my own function for 3 values ββin a formula with signs such as: '+', '-', '*', '/'.
Function Code:
use db_test; go alter function dbo.eval(@a varchar(max)) returns float as begin set @a = replace(@a, ' ', ''); declare @pos1 int = PATINDEX('%[+/*-]%', @a); declare @t1 float = cast(substring(@a, 1, @pos1 - 1) as float); declare @sign1 char(1) = substring(@a, @pos1, 1); set @a = substring(@a, @pos1 + 1, len(@a) - @pos1); declare @pos2 int = PATINDEX('%[+/*-]%', @a); declare @t2 float = cast(substring(@a, 1, @pos2 - 1) as float); declare @sign2 char(1) = substring(@a, @pos2, 1); set @a = substring(@a, @pos2 + 1, len(@a) - @pos2); declare @t3 float = cast(@a as float); set @t1 = ( case @sign1 when '+' then @t1 + @t2 when '-' then @t1 - @t2 when '*' then @t1 * @t2 when '/' then @t1 / @t2 end ); set @t1 = ( case @sign2 when '+' then @t1 + @t3 when '-' then @t1 - @t3 when '*' then @t1 * @t3 when '/' then @t1 / @t3 end ); return @t1; end;
And he is working on the following data:
select dbo.eval('7.6*11.3/4.5') as eval, 7.6*11.3/4.5 as sqlServerCalc; eval sqlServerCalc 19,0844444444444 19.084444
After that, you can replace the values ββin the formula with the values ββof the columns and calculate them:
with cte as ( select rn, t1, t2, t3, formula, REPLACE(REPLACE(REPLACE(formula, 't1', cast(t1 as varchar(max))), 't2', cast(t2 as varchar(max))), 't3', cast(t3 as varchar(max))) as calc from db_test.dbo.loop ) select rn, t1, t2, t3, formula, db_test.dbo.eval(calc) as result into db_test.dbo.loop2 from cte;
Time is right for me, it takes 3 minutes on my Sql 2016 server and gives good results:
select top 5 * from db_test.dbo.loop2; rn t1 t2 t3 formula result 1 80 23 93 t1 / t2 * t3 323,478260869565 2 80 87 30 t1 / t2 * t3 27,5862068965517 3 92 83 63 t1 / t2 * t3 69,8313253012048 4 68 19 36 t1 / t2 * t3 128,842105263158 5 65 63 10 t1 / t2 * t3 10,3174603174603
If you have a list of all the operations that are applicable in the formula, you can write a general function for several variables. But if there is something more complicated in the formula, then you should use the CLR.