将字符串中的算术公式转换为值 [英] Converting arithmetic formula in a string into a values

查看:25
本文介绍了将字符串中的算术公式转换为值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,其中所有条目都采用算术公式的形式(即 1+2+3 等).

I have a table in which all entries are in form of arithmetic formulas (i.e. 1+2+3 etc).

在此表中,所有列的类型都是 varchar.该表有许多这样的列.

In this table all columns are of type varchar. The table has many columns like this.

我想计算公式并将值插入另一个.关于如何实现这一目标的任何建议?

I want to calculate formula and insert the values into another. Any suggestions on how to achieve this?

推荐答案

你可以试试这个.我希望这可以帮助你.它从 t1 中获取表达式并将结果放入 t2.您不会希望 t1 成为实际表,因为它从表中删除,因此您可以将实际表值复制到临时表

You can try this. I hope this can assist you. It takes expression from t1 and put the result in t2. You won't want to make t1 the actual table as it deletes from the table, so you can copy the actual table value to a temp table

declare @t as table(val varchar(20))
declare @t2 as table(val varchar(20))
insert into @t values
('1+3'),
('2*3'),
('9+3*2')


declare @exp varchar(20)
while(exists(select 1 from @t))
begin
    select top(1) @exp = val from @t

    insert into @t2
    exec ('select '+@exp)  

    delete top (1) from @t
end

select * from @t2

结果

val
------
4
6
15

您可以查看这些链接这里有类似问题将带表达式的字符串转换为十进制

这篇关于将字符串中的算术公式转换为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆