NateTheGreat NateTheGreat - 1 year ago 62
SQL Question

SQL Evaluate formula stored in database

Is it possible to evaluate a string formula/expression stored in a column? (SQL Server 2014).


ID | Formula
1 | IIF(2<3,'A','B')
2 | IIF(3<4,'C','D')
3 | IIF(5<1,'E','F')


SELECT ID, Eval(Formula)


1 | A
2 | C
3 | F

Answer Source

With Dynamic SQL, but REALLY not recommended. Just in case you REALLY have to...

Declare @YourTable table (ID int,Formula varchar(100))
Insert Into @YourTable values

Declare @SQL varchar(max) = '>>>'

Select @SQL = Replace(@SQL + concat(' Union All Select ID=',ID,',Value=',Formula),'>>> Union All','')
 From  @YourTable

Exec (@SQL)


ID  Value
1   A
2   C
3   F
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download