Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute column values in SQL Server [duplicate]

Tags:

sql

sql-server

I need to do an arithmetic operation to the values saved in SQL table, for example, I have value as 5*10 in next column I want 15

EQUATION    VALUE
2+5          7
6+8          14

Based on the equation I need to calculate the value.

like image 205
Girish A Avatar asked Oct 20 '25 04:10

Girish A


1 Answers

As you know by now, SQL Server does not have an EVAL() function. However, with a little dynamic SQL, it is possible, but really not recommended.

Example

Declare @YourTable Table (id int,[EQUATION] varchar(150))
Insert Into @YourTable Values 
 (1,'2+5')
,(2,'6+8')
,(3,'datediff(DAY,''2018-01-01'',getdate())')  -- Added Just for Fun


Declare @SQL varchar(max) = Stuff((Select ',' + concat('(',ID,',',[EQUATION],')')
                                     From @YourTable  A
                                     For XML Path (''))
                                 ,1,1,'')
Exec('Select * from (values ' + @SQL + ')A([ID],[Value])')

Returns

ID  Value
1   7
2   14
3   189
like image 190
John Cappelletti Avatar answered Oct 22 '25 18:10

John Cappelletti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!