在SQL Server中执行列值[重复](Execute column values in SQL Server [duplicate])

编程入门 行业动态 更新时间:2024-10-27 19:15:42
在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 answers

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.

最满意答案

如您所知,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 189

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

更多推荐

本文发布于:2023-08-06 06:55:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1445988.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Execute   Server   SQL   duplicate   values

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!