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.
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.
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
Just execute the operation as a SELECT
statement
declare @col1 nvarchar(50) = '10+5'
DECLARE @STATEMENT NVARCHAR(50) = 'SELECT'
DECLARE @COMMAND NVARCHAR(50) = @STATEMENT + ' ' + @COL1
exec sp_executesql @COMMAND
Output:
15