在SQL Server中执行列值[重复](Execute column values in SQL Server [duplicate])
这个问题在这里已有答案:
在数据库中存储公式(方程式)以便稍后评估(SQL Server 2005) 4个答案我需要对SQL表中保存的值进行算术运算,例如,我在下一列中的值为5 * 10我希望15
EQUATION VALUE 2+5 7 6+8 14基于等式,我需要计算该值。
This question already has an answer here:
Storing formula (equations) in database to be evaluated later (SQL Server 2005) 4 answersI 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 14Based on the equation I need to calculate the value.
最满意答案
如您所知,SQL Server没有EVAL()函数。 但是,使用一点动态SQL,它是可能的, 但实际上不推荐 。
例
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])')返回
ID Value 1 7 2 14 3 189As 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更多推荐
发布评论